JAXB: Problem generating java enums

Hi
I'm having som problems configuring JAXB to generate type safe enums. The schema I'm using has several structures similar to this simplified example:
    <xs:element name="Car">
        <xs:complexType>
            <xs:sequence>
                <xs:element name="CarTypeEnumInComplexType">
                    <xs:simpleType>
                        <xs:restriction base="xs:string">
                            <xs:enumeration value="Truck"/>
                            <xs:enumeration value="Jeep"/>
                            <xs:enumeration value="SUV"/>
                        </xs:restriction>
                    </xs:simpleType>
                </xs:element>
            </xs:sequence>
        </xs:complexType>
    </xs:element>In the resulting Java code CarTypeEnumInComplexType is just generated as a String value in the Car Interface.
What I really want is a separate Java class for "CarTypeEnumInComplexType" - with constants for each enumeration value.
However, I do not want to change the schema - as this is maintained by another company.
For a moment I thought I'd found the solution: By setting the global binding setting "typesafeEnumBase" to "xs:string" I made JAXB generate this kind of enumeration classes in cases like this:
<xs:simpleType name="CarTypeEnum">
        <xs:restriction base="xs:string">
            <xs:enumeration value="Truck"/>
            <xs:enumeration value="Jeep"/>
            <xs:enumeration value="SUV"/>
        </xs:restriction>
    </xs:simpleType>However, I still can't make this work for enumerations nested within a complex type as illustrated in the first example.
I'm new to XML schemas and JAXB - so I may be missing something obvious here...
Is there any way to make JAXB generate an enum class for "CarTypeEnumInComplexType" in my first example without altering the schema structure?
Vidar

Well I couldnt really find any clear documentation to this , however with this post I was able to get going in the right direction I thought I would post the solution here.
This assumes you have some control of your schema , it doesnt solve the problem where you cant touch the schema at all.
So first my bindings.xjb file looks like:
<?xml version="1.0"?>
<jxb:bindings version="1.0" xmlns:jxb="http://java.sun.com/xml/ns/jaxb" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xjc="http://java.sun.com/xml/ns/jaxb/xjc" jxb:extensionBindingPrefixes="xjc">
     <jxb:bindings schemaLocation="CMSOSS.xsd" node="/xs:schema">
          <jxb:globalBindings typesafeEnumBase ="xs:string">
               <xjc:serializable uid="12343"/>
          </jxb:globalBindings>
          <jxb:schemaBindings>
               <jxb:package name="com.cms.oss"/>
               <jxb:nameXmlTransform>
                    <jxb:elementName suffix="Element"/>
               </jxb:nameXmlTransform>
          </jxb:schemaBindings>
     </jxb:bindings>
</jxb:bindings>
First its necessary to have the enum type defined outside of the complex type:
<xs:simpleType name="serviceTypeEnum">
          <xs:annotation>
               <xs:documentation>Type of service being added (RES, BUS, FAX, POTS)</xs:documentation>
          </xs:annotation>
          <xs:restriction base="xs:string">
               <xs:enumeration value="RES"/>
               <xs:enumeration value="BUS"/>
               <xs:enumeration value="FAX"/>
               <xs:enumeration value="POTS"/>
          </xs:restriction>
     </xs:simpleType>
Then you can use the enum in your complex type in the following manner
     <xs:element name="service">
          <xs:annotation>
               <xs:documentation>Create a service tag for each new line of service</xs:documentation>
          </xs:annotation>
          <xs:complexType>
               <xs:sequence>
                    <xs:element ref="phone"/>
                    <xs:element name="type" type="serviceTypeEnum">
                         <xs:annotation>
                              <xs:documentation>Type of service being added (RES, BUS, FAX, POTS)
                              </xs:documentation>
                         </xs:annotation>
                    </xs:element>
                    <xs:element ref="lineDevice"/>
                    <xs:element ref="LNP" minOccurs="0"/>
                    <xs:element ref="VMPIN"/>
                    <xs:element ref="location"/>
                    <xs:element name="userService" minOccurs="0" maxOccurs="unbounded"/>
               </xs:sequence>
          </xs:complexType>
     </xs:element>
Some better documentation on this would sure help ... however I dont think this solves completely the original problem...
I would think that type safe enums should be built into the specification without all this custom binding stuff.
R
S

Similar Messages

  • JAXB problem generating java classes

    I'm doing some integration and have received a schema from the vendor the other day. When I try to generate java classes with the jaxb compiler I get this output
    parsing a schema...
    [ERROR] Property "Value" is already defined.
      line 14 of jar:file:/C:/win32app/Java/jdk6/lib/tools.jar!/com/sun/xml/internal/xsom/impl/parser/datatypes.xsd
    [ERROR] The following location is relevant to the above error
      line 384 of file:/C:/code/sca-ecr.xsd
    Failed to parse a schema.
        <xsd:complexType name="options">
            <xsd:sequence>
                <xsd:element name="option" maxOccurs="unbounded">
                    <xsd:complexType>
                        <xsd:simpleContent>
                            <xsd:extension base="xsd:string">
    (Line 384)                  <xsd:attribute name="value" type="xsd:string"/>
                            </xsd:extension>
                        </xsd:simpleContent>
                    </xsd:complexType>
                </xsd:element>
            </xsd:sequence>
        </xsd:complexType>So, googling about this I came across these to articles that almost describes my problem.
    http://weblogs.java.net/blog/kohsuke/archive/2005/05/compiling_mathm_1.html
    https://jaxb.dev.java.net/guide/Dealing_with_errors.htmlAdding the this code did not help. Downloading JAXB 2.1.4 did not help, adding the -extension parameter still same result.
            <xsd:annotation>
              <xsd:appinfo>           
                <jaxb:property name="someAttribute" />
              </xsd:appinfo>
            </xsd:annotation>      Why is jaxb failing ? Could it be that and attribute is not allowed to be called "value" ?
    Any answers will do
    regards abq

    Well, after hours of digging I found a solution which actually was right in front of me the whole time.
    This is how I edited the schema.
        <xsd:complexType name="options">
            <xsd:sequence>
                <xsd:element name="option" maxOccurs="unbounded" >
                    <xsd:complexType>
                        <xsd:simpleContent>
                            <xsd:extension base="xsd:string">
                               <xsd:attribute name="value" type="xsd:string" >
                                  <xsd:annotation><xsd:appinfo>
                                    <jaxb:property name="realValue" />
                                  </xsd:appinfo></xsd:annotation>
                                 </xsd:attribute>
                            </xsd:extension>
                        </xsd:simpleContent>
                    </xsd:complexType>
                </xsd:element>
            </xsd:sequence>
        </xsd:complexType>Before, I placed the <xsd:annotation> tag efter the first line but inside the <xsd:attribute> made much better if you would like it to work.
    When marshling an @XmlRoot object will produce valid xml code. So even though that the server have a different xml schema, they will be able to talk to each other.
    abq

  • JAXB to generate java classes for XSD.

    Hi
    I have a XSD, which is importing other couple of xsds in it, tried to generate java classes using xjc, it is throwing error.
    C:\vittal\Project\received\development-1\da_xsd>xjc -p com daAuthoring.xsd
    parsing a schema...
    [ERROR] Property "Alt" is already defined. Use <jaxb:property> to resolve thi
    s conflict.
      line 42 of file:/C:/vittal/Project/received/development-1/da_xsd/commonElement
    s.xsd
    [ERROR] The following location is relevant to the above error
      line 2205 of file:/C:/vittal/Project/received/development-1/da_xsd/daCommonEle
    ments.xsd
    Failed to parse a schema.Please let me know how to fix this issue.

    Thanks for information,
    I do understand xml well, and having basic knowledge on XSD.
    1. can i generate a java classes for a xsd which is including other XSDs.
    2. how to overwrite the issue, using annotation, point me to a location where i will get more information, that will be great help.
    here is my xsd.
    <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:ditaarch="http://dita.oasis-open.org/architecture/2005/" xmlns:dctm="http://www.documentum.com" elementFormDefault="qualified">
         <xs:import namespace="http://dita.oasis-open.org/architecture/2005/" schemaLocation="ditaarch.xsd"/>
         <xs:import namespace="http://www.documentum.com" schemaLocation="dctmAttrs.ent.xsd"/>
         <xs:import namespace="http://www.w3.org/XML/1998/namespace" schemaLocation="xml.xsd"/>
         <xs:group name="alt">
              <xs:sequence>
                   <xs:element ref="alt"/>
              </xs:sequence>
         </xs:group>
         <xs:group name="desc">
              <xs:sequence>
                   <xs:element ref="desc"/>
              </xs:sequence>
         </xs:group>
         <xs:group name="title">
              <xs:sequence>
                   <xs:element ref="title"/>
              </xs:sequence>
         </xs:group>
         <!-- Elements in tblDecl.mod -->
         <xs:group name="colspec">
              <xs:sequence>
                   <xs:element ref="colspec"/>
              </xs:sequence>
         </xs:group>
         <xs:group name="entry">
              <xs:sequence>
                   <xs:element ref="entry"/>
              </xs:sequence>
         </xs:group>
         <xs:group name="row">
              <xs:sequence>
                   <xs:element ref="row"/>
              </xs:sequence>
         </xs:group>
         <xs:group name="tbody">
              <xs:sequence>
                   <xs:element ref="tbody"/>
              </xs:sequence>
         </xs:group>
         <xs:group name="tgroup">
              <xs:sequence>
                   <xs:element ref="tgroup"/>
              </xs:sequence>
         </xs:group>
         <xs:group name="thead">
              <xs:sequence>
                   <xs:element ref="thead"/>
              </xs:sequence>
         </xs:group>
    </xs:schema>

  • JAXB - Generated Java Classes error

    Hi,
    I am having a problem generating java classes given the follow snippet from a DTD. The ImplemenationData class that is generated does not include ImplementationPlatform and ProgramParameters as attributes. Instead, it includes these two elements in the PredicatedLists and then generates a content exception when those elements are not found. Can anyone tell me why these two elements are not being generated as attributes with the associated setter/getter methods to go with them? The ExeOptions, DllOptions and ExternalOptions are being generated properly and included in the PredicatedLists as they should be. Any help would be greatly appreciated.
    <!ELEMENT ImplementationPlatform           (#PCDATA)>
    <!ELEMENT ProgramParameters                (#PCDATA)>
    <!ELEMENT ImplementationData
         (ImplementationPlatform,
         ProgramParameters,
         (ExeOptions
         |DllOptions
         |ExternalOptions))>
    <!ELEMENT ExeOptions
         (PathAndFileName,
         WorkingDirectoryName?,
         Environment?,
         InheritEnvironment,
         StartInForeGround?,
         AutomaticClose?,
         WindowStyle?,
         RunInXTerm?)>
    <!ELEMENT DllOptions
         (PathAndFileName,
         EntryPointName,
         ExecuteFenced?,
         KeepLoaded?)>
    <!ELEMENT ExternalOptions
         (ServiceName,
         ServiceType,
         InvocationType,
         ExecutableName,
         ExecutableType,
         IsLocalUser,
         IsSecurityRoutineCall,
         CodePage?,
         TimeoutPeriod,
         TimeoutInterval?,
         IsMappingRoutineCall,
         MappingType?,
         ForwardMappingFormat?,
         ForwardMappingParameters?,
         BackwardMappingFormat?,
         BackwardMappingParameters?)>

    Just a thumb suck but, have you tried placing the defintitions after the declarations instead of before.
    Dave

  • Mapping Generated JAXB Classes to JAVA Classes

    Hi,
    i�m writing a framework to allow building swing components from xml files. So i use JAXB to generate the stubs and then in
    my JAVA app i do an unmarshal process to get the jaxb elements. Then i process all the elements in the jaxb tree and
    i create the corresponding swing components (i.e. JPanel, GridLayout, JButton, JTextField, etc). This is very annoying,
    since each component has different properties and this leads to many if statements which just make my code messy
    and not reusable.
    Could someone give me an advice of how i could make this solution more elegant?
    Thanks for any ideas,
    Chris

    Hi,
    Can you please let me know if you found a solution? I have the same exact problem. I have pretty solid collection of similar questions in the NET, but not a single answer yet... Keep searching...
    Thanks!
    Rouben.
    P.S can you please CC your answer to [email protected]?

  • Problem generating stubs for Java EJB web service deployed in OAS

    I created an EJB web service and I've successfully deployed it in my Oracle App Server. Some of the methods work fine but others produce the ff error:
    org.apache.soap.SOAPException - java.lang.IllegalArgumentException: No Serializer found to serialize [classname] using encoding style [encoding]It seems that the objects specified as parameters in the web service methods exposed are the only ones that had stubs generated for them. Other objects I use, which are usually wrapped inside a Vector, did not have generated stubs.
    Example:
         public String loginUser(UserDTO userDTO) throws RemoteException, NamingException, SQLException;
    public String addItems (Vector vecItems) throws RemoteException, NamingException, SQLException; // where vecItems is a collection of ItemDTO objects     In this scenario, stubs were generated for the UserDTO class, but not for the ItemDTO class. In effect, calling the addItems method resulted to the exception I mentioned above.
    I did a workaround wherein I declared a dummy method which accepted all the types of objects I needed as parameters so all the necessary stubs can be generated, but this fix doesn't feel like it's the proper solution to my problem.
    If anyone can help me, it would be greatly appreciated. Thanks!

    Crossposted:
    Problem generating stubs for Java EJB web service deployed in OAS

  • How to generate .xsd file using jaxb generated java files

    Hi,
    We need to upgrade our applicatio to jdk1.6 which has jaxb2.0 class files in it. Our application has java files generated from .xsd using jaxb1.0.2 version. At present we dont have .xsd or .xml file with us.
    We decide to generate .xsd file by using jaxb1.0.2 generated java files. I tried using schemagen.exe given by jdk1.6 to generate .xsd file. It error out. Is there any other way to generate .xsd file ?
    pls let me know.
    thanks,
    Thiru

    Object-XML mapping is a new feature in JAXB 2.0. Classes generated with JAXB 1.0 won't generate a schema.
    Generate Java classes with JAXB 2.0 xjc.
    http://www.theregister.co.uk/2006/09/22/jaxb2_guide/

  • Problem in generate Java  from PL SQL package in Jdeveloper

    Hi
    i have problem in create java class from PL SQL package in JDeveloper.
    I use Database navigator of jdeveloper and right click on a package and choose Generate Java then in Jpublisher window choose my view Controller and accept other default values.
    I call methods of generated class in the Action of a button in my JSP page, but when I click the button it  throw null pointer exception !!! i fund one of generated method return null and it lead to this exception.
    protected DefaultContext __tx = null;
    public DefaultContext getConnectionContext() throws SQLException  {
    if (__tx==null){
    __tx = (getConnection()==null) ? DefaultContext.getDefaultContext() : new DefaultContext(getConnection());
        return __tx;
      public Connection getConnection() throws SQLException
        if (__onn!=null) return __onn;
         else if (__tx!=null) return __tx.getConnection();
         else if (__dataSource!=null) __onn= __dataSource.getConnection();
         return __onn;
    i try to generate class in Model project and create DataControl for that and use method action but noting change and i get null pointer again!!
    Jdeveloper Versino = 11.1.1.7.0

    Let me ask you another question: Why do you generate java from the package at all?
    Where do you want to call the package?
    Back to your question: you should see code like
        public void setDataSourceLocation(String dataSourceLocation) throws SQLException {
            javax.sql.DataSource dataSource;
            try {
                Class cls = Class.forName("javax.naming.InitialContext");
                Object ctx = cls.newInstance();
                java.lang.reflect.Method meth = cls.getMethod("lookup", new Class[] { String.class });
                dataSource = (javax.sql.DataSource) meth.invoke(ctx, new Object[] { "java:comp/env/" + dataSourceLocation });
                setDataSource(dataSource);
            } catch (Exception e) {
                throw new java.sql.SQLException("Error initializing DataSource at " + dataSourceLocation + ": " + e.getMessage());
    in the generated code. This code look up a datasource (which you have defined e.g. on the Weblogic Server) by calling the method
    setDataSourceLocaltion("jdbc/HRConnDS");
    This look up the datasource nad stores it in the class variable.
    Timo

  • Preventing JAXB xjc from re-generating java code of import ed schemas...

    Hi, I am using XJC to generate java code from xsd.
    However the xsd I run it on often has imports to another xsd that will be in a jar along with its java classes already existing.
    This jar is on the calsspath too.
    XJC however not only generates java code for existing xsd, but also for every import it has.
    And also for every import each of those imported xsd's might have.
    So if it were a long import chain A->B->C->D it generates code for all.
    How can i get it to generate code for only A and assume all the remaing code can be found on the jars in the classpath.
    The A.xsd also has a catalog file associated with it that has every namespace reference pointing to the correct xsd locations within jars.
    So it even has B->C mapping and C->D mapping. This was needed or else XJC didnt even generate anything at all and complained it could not reach C from B and so on.
    Catalog file solved that problem but not the fact that it keeps regnerating code.
    Thanks
    Edited by: Priyajeet on Dec 9, 2008 1:36 PM

    Problem solved.
    The xjc compiler reads file name in a case-sensitive fashion, even on windows.
    So, common.xsd and Common.xsd are seen as two distinct files.
    This was the cause of the compilation errors, since feature1 imported the schema using the filename Common.xsd, whereas the other schemas imported common using common.xsd
    I hope this could help.
    Salvatore

  • Problems to generate JAVA from SQLJ

    Hi, i work with Developer 10.1.3, and I try to generate files .java from files .sqlj. I generate java files from de packages in data base, but don´t generate me files .java from the .sqlj generated. Can anyone help me?
    Regards.

    Hi,
    Does it happen for a particular work area or any workarea?
    Can you give the detail of the Designer client you are using?
    The following steps should be follwed:
    Select Database as "Source of Design Capture"
    Give the correct database connection detail
    Give the correct Target Container, Capture Implementation Info and User.
    Select the object(s) to be captured
    Click the Start button

  • Special Characters issue in JAXB Classes generated

    Hi,
    I have generated Java bean classes from an xml schema using JAXB 2.0 Content Model feature in Jdeveloper 11g. I have another class, which has a method testMethod which takes the Java Bean class object as input. I have exposed this method as java webservice. I am just printing the FirstName from the input I have got.
    public String testMethod(TestBean testbean) {
    testBean,getContact().getFirstName();
    When there are some special characters like �, my java bean accepts and displays as �. I printed the value directly in my getter method, but it prints differently.
    How can I set my Java Bean class to use ISO-8859-1 as encoding.

    Sorry but this has nothing to do with ADF. Please try in the right forum here https://forums.oracle.com/forums/category.jspa?categoryID=285

  • Errors generating Java classes from XML schema

    I received the following errors when generating Java classes from the schema located at: http://imsproject.org/xsd/ims_qti_rootv1p1.xsd and http://imsproject.org/xsd/ims_xml.xsd
    XML Spy v4 claims that the schema is well-formed and valid. Could this be a problem with the class generators, or is XML Spy not telling the truth?
    Thanks.
    D:\IMS_QTI\Java>java -classpath .;lib/xmlparserv2.jar;lib/xschema.jar;lib/classgen.jar oracle.xml.classgen.oracg -schema ims_qti_rootv1p1.xs
    d -outputDir src\com\icld\qti -package com.icld.qti -comment
    file:/D:/IMS_QTI/Java/ims_qti_rootv1p1.xsd<Line 235, Column 21>: XSD-2209: (Error) Duplicated definition for: 'attr.view'
    file:/D:/IMS_QTI/Java/ims_qti_rootv1p1.xsd<Line 303, Column 21>: XSD-2209: (Error) Duplicated definition for: 'grp.labels'
    file:/D:/IMS_QTI/Java/ims_qti_rootv1p1.xsd<Line 1834, Column -12236>: XSD-2209: (Error) Duplicated definition for: 'qtimetadatafield'
    file:/D:/IMS_QTI/Java/ims_qti_rootv1p1.xsd<Line 1834, Column -9642>: XSD-2209: (Error) Duplicated definition for: 'typeofsolutionType'
    file:/D:/IMS_QTI/Java/ims_qti_rootv1p1.xsd<Line 2252, Column -3019>: XSD-2026: (Error) Invalid attribute 'use' in element 'attribute'
    Error: Schema Class Generator failed to generate classes. oracle.xml.parser.schema.XSDException: Duplicated definition for: 'attr.view'

    <BLOCKQUOTE><font size="1" face="Verdana, Arial">quote:</font><HR>Originally posted by Jinyu Wang ([email protected]):
    Which version are you using? I can't reproduce the error with 9.0.2B version.<HR></BLOCKQUOTE>
    Thanks for having a look at the problem. I am using the 9.0.2.0B version with Java 2 Standard Edition Build 1.3.1-b24. The classgen -version option returns 9.0.2.0b-beta - and xmlparserv2.jar and xschema.jar are from the same distribution. Running the corresponding DTD from the same source work fine - I'm just havinf this problem with the XSD. Anything else I should look at?

  • How to omit xmlns from generated Java classes

    Hi,
    I'm using JAXB and xjc to generate Java classes from xsd fils. I've noticed that when marshalling these Java classes to XML string, there are few xmlns attributes that (as far as I concern :-))
    "waste" space on the generated xml (space is critical resource in our application). Is there a way to order the Marashaller to omit these xmlns attributes from the generated files?
    I tried to edit the generated xml string. I removed the xmlns attributes, but unmarshall it back to Java objects failed...
    Thanks for any help,
    Barak.

    If the xmlns is specified in the xsd, it is also required in the xml. If you do not want it, however you can remove it from your xsd and then generate your xml

  • About generating Java classes from XSD Schema ???

    I need a powerfull tool to generate Java classes from XML Schema. I want that generated classes to have the option to validate XML(to be JAXP1.2 compliant).
    I used XML Spy 5.4 but the generated classes can't validate an XML file.
    Can you help me with other tools that:
    - generate Java classes from XSD
    - generate sample XML from XSD
    - are JAXP1.2 compliant(validate a XML file with a schema)
    Thanks.

    You can also use Castor: http://www.castor.org
    It generates classes from XML Schemas and enables data
    binding without writing any line of a fuckin SAX
    parser :-)I evaluated Castor and JAXB and while JAXB isn't perfect, it's got some things over Castor. Castor almost looks abandonded when I go to the site. The documentation just sort of trails off.

  • JAXB 1 : generating simpleTypes classes

    Sorry, I posted an uncompleted message.
    Hello, I'm new to JAXB technology.
    Since I'm working with j2sdk 1.4 I c'ant use JAXB 2, so I'm using JAXB 1.0.6.
    When I call the xjc ant task, my java classes are generated... buy simple types do not generate any java class.
    Let's say I have the following xsd:
    <xs:complexType name="EXAMPLE">
    <xs:sequence>
    <xs:element name="market-type" type="po:market-type"/>
    </xs:sequence>
    </xs:complexType>
    <xs:simpleType name="MARKET-TYPE">
    <xs:restriction base = "xs:string">
    <xs:enumeration value = "PRIM"/>
    <xs:enumeration value = "SECOND"/>
    </xs:restriction>
    </xs:simpleType> After xjc compilation I have a EXAMPLE Java class, but its element "market-type" is a String and not a MARKET-TYPE as I expected.
    Is it normal? Can I customize the output in order to generate java classes for simpleTypes?

    The base data type of the simpleType MARKET-TYPE is xsd:string.

Maybe you are looking for

  • Problem transferring purchased files from Yahoo Jukebox to I-tunes

    Any ideas here? Do I have to take my I-pod back and buy a zune or some other non-apple mp3 player? I bought a significant number of files under Musicmatch--which then switched over to Yahoo--Jukebox. Bought and paid for them. I- Tunes refuses to allo

  • My email provider says I need to clear the cache - toolbar doesnt' display

    I don't know how to make the toolbar display so I can click on tools to go in and clear my cache or clear my cookies. Please help

  • Constant selection in Crystal Reports (like BEx)

    Hello! I'am sorry if this question have printed answer already but I can't found it. I have BEx report like this:           month1                   month2                         monthN items     amount                   amount                      

  • Alienware M14XR2 open box transfer of ownership

    I  bought an open box Alienware M14XR2 at Best buy two days ago... The laptop is in good condition where it includes everything and sealed (it looks brand new). So, when I called Dell to request for a Windows 8 installation disk to do a full re-insta

  • How to install Real Time Conference component?

    Hello everybody! It's possible to install the "OC4J_imeeting" the OCS webconference component, when i've an already installed and configured OCS infra and middle tier? If it can be done, how can i do it? Trough OUI? I don't have the "OC4J_meeting" li