Error in Generating an Java POJO from XML Schema that Contains Imports

I am working on a project where I need to automatically generate code for a POJO-like object from an XML Schema (XSD) file. To achieve this, I have created a class that takes the file path of the XSD as input and generates the corresponding code as a string.

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URI;
import java.util.Arrays;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import org.xml.sax.InputSource;

import com.sun.codemodel.JCodeModel;
import com.sun.codemodel.CodeWriter;
import com.sun.tools.xjc.api.ClassNameAllocator;
import com.sun.tools.xjc.api.S2JJAXBModel;
import com.sun.tools.xjc.api.SchemaCompiler;
import com.sun.tools.xjc.api.XJC;
import com.sun.codemodel.writer.SingleStreamCodeWriter;

public class SemanticPOJOCreator {

    public static String fromXSD(String xsdFilePath, String outClassName) throws IOException {
        SchemaCompiler sc = XJC.createSchemaCompiler();
        sc.forcePackageName("");

        sc.setClassNameAllocator(new ClassNameAllocator() {
            public String assignClassName(String packageName, String className) {
                return outClassName;
            }
        });
        
        File schemaFile = new File(xsdFilePath);
        try (FileInputStream fis = new FileInputStream(schemaFile)) {
            InputSource is = new InputSource(fis);
            URI uri = schemaFile.toURI();
            is.setSystemId(uri.toASCIIString());

            sc.parseSchema(is);
            S2JJAXBModel model = sc.bind(); // Here
            JCodeModel jCodeModel = model.generateCode(null, null);
            
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            CodeWriter codeWriter = new SingleStreamCodeWriter(baos);

            jCodeModel.build(codeWriter);

            String generatedCode = baos.toString();
            
            generatedCode = Arrays.stream(generatedCode.split("n"))
                    .map(line -> {
                        if (line.startsWith("public class")) {
                            return line.replace("public class", "class");
                        } else {
                            return line;
                        }
                    })
                    .filter(line -> !line.startsWith("import") && !line.contains("-----"))
                    .collect(Collectors.joining("n"));
            
            generatedCode = generatedCode.replaceAll("ObjectFactory", "ObjectFactory_" + outClassName);   
            
            return generatedCode;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}

The class works correctly with most XSD files. However, it triggers an error when the file contains an <xs:import> element. Below is an example of the XSD file causing the issue:

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

<xs:schema 
      attributeFormDefault="unqualified" 
      elementFormDefault="qualified" 
      xmlns:xs="http://www.w3.org/2001/XMLSchema" 
      xmlns:a3st ="http://gres.uninova.pt/a3st" 
      xmlns:sawsdl="http://www.w3.org/ns/sawsdl"
      xmlns="urn:oasis:names:specification:ubl:schema:xsd:Invoice-2"
      xmlns:cac="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2"
      xmlns:cbc="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2"
      xmlns:ext="urn:oasis:names:specification:ubl:schema:xsd:CommonExtensionComponents-2">
   
<xs:import namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2"
schemaLocation="../common/UBL-CommonAggregateComponents-2.1.xsd"/>
<xs:import namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2"
schemaLocation="../common/UBL-CommonBasicComponents-2.1.xsd"/>
<xs:import namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonExtensionComponents-2"
schemaLocation="../common/UBL-CommonExtensionComponents-2.1.xsd"/>

   <xs:complexType name="InvoiceType">
      <xs:sequence>
         <xs:element ref="cac:AllowanceCharge"  sawsdl:modelReference ="/TemperatureSensor{2}/hasDecValue">         
         </xs:element>      
         <xs:element ref="cac:TaxTotal">
         </xs:element>   
      </xs:sequence>
   </xs:complexType>
</xs:schema>

The error encountered is consistentently Exception in thread "main" java.lang.IllegalArgumentException: the root package cannot be annotated and occurs at S2JJAXBModel model = sc.bind();.

If the sc.forcePackageName(""); line is omitted, a different error occurs:

Exception in thread "main" java.lang.NullPointerException: Cannot invoke "com.sun.tools.xjc.api.S2JJAXBModel.generateCode(com.sun.tools.xjc.Plugin[], com.sun.tools.xjc.api.ErrorListener)" because "model" is null

Is the issue I’m encountering a limitation of the libraries or packages I am using, or could it be due to incorrect usage or configuration on my part?

New contributor

Afonso Oliveira is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

1

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật