CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/maven-org-glassfish-jaxb--jaxb-xjc

JAXB Binding Compiler (XJC) that generates Java classes from XML Schema definitions with both command-line and programmatic APIs

Pending
Overview
Eval results
Files

programmatic-api.mddocs/

Programmatic API

The JAXB XJC programmatic API provides type-safe Java interfaces for embedding schema compilation in applications, build tools, and IDEs with full control over the compilation process.

Capabilities

Main API Entry Point

Central factory class for creating schema compilers and utility functions.

/**
 * Entry point to the programmatic API for schema compiler (XJC)
 */
public final class XJC {
    /**
     * Gets a fresh SchemaCompiler instance
     * @return always return non-null SchemaCompiler object
     */
    public static SchemaCompiler createSchemaCompiler();
    
    /**
     * Computes namespace URI to package name conversion per JAXB spec
     * @param namespaceUri Namespace URI. Can be empty but must not be null
     * @return Java package name or null if conversion fails
     */
    public static String getDefaultPackageName(String namespaceUri);
}

Usage Example:

import com.sun.tools.xjc.api.XJC;
import com.sun.tools.xjc.api.SchemaCompiler;

// Create new compiler instance
SchemaCompiler compiler = XJC.createSchemaCompiler();

// Convert namespace to package name
String packageName = XJC.getDefaultPackageName("http://example.com/schema");
// Returns: "com.example.schema"

Schema Compilation Interface

Core interface for parsing schemas and controlling compilation process.

/**
 * Schema-to-Java compilation interface with full configuration options
 */
public interface SchemaCompiler {
    /**
     * Get SAX ContentHandler for parsing schemas
     * @param systemId System identifier for the schema
     * @return ContentHandler for SAX parsing
     */
    ContentHandler getParserHandler(String systemId);
    
    /**
     * Parse schema from InputSource
     * @param source InputSource containing schema content
     */
    void parseSchema(InputSource source);
    
    /**
     * Parse schema from DOM Element
     * @param systemId System identifier for the schema
     * @param element DOM element containing schema
     */
    void parseSchema(String systemId, Element element);
    
    /**
     * Parse schema from XMLStreamReader
     * @param systemId System identifier for the schema  
     * @param reader StAX XMLStreamReader positioned at schema
     */
    void parseSchema(String systemId, XMLStreamReader reader);
    
    /**
     * Set target JAXB specification version
     * @param version Target specification version
     */
    void setTargetVersion(SpecVersion version);
    
    /**
     * Set error listener for compilation messages
     * @param errorListener Listener for errors, warnings, and info messages
     */
    void setErrorListener(ErrorListener errorListener);
    
    /**
     * Set entity resolver for schema imports/includes
     * @param entityResolver Resolver for external entities
     */
    void setEntityResolver(EntityResolver entityResolver);
    
    /**
     * Set default package name for generated classes
     * @param packageName Package name for classes without explicit namespace mapping
     */
    void setDefaultPackageName(String packageName);
    
    /**
     * Force all generated classes into specified package
     * @param packageName Package name to use for all generated classes
     */
    void forcePackageName(String packageName);
    
    /**
     * Set custom class name allocation strategy
     * @param allocator Custom allocator for resolving class name conflicts
     */
    void setClassNameAllocator(ClassNameAllocator allocator);
    
    /**
     * Clear all parsed schemas and reset compiler state
     */
    void resetSchema();
    
    /**
     * Compile parsed schemas and create binding model
     * @return S2JJAXBModel containing compilation results, or null if compilation failed
     */
    S2JJAXBModel bind();
    
    /**
     * Get compilation options (deprecated - for compatibility)
     * @return Options object
     * @deprecated Use specific setter methods instead
     */
    @Deprecated
    Options getOptions();
}

Usage Example:

import com.sun.tools.xjc.api.*;
import javax.xml.transform.stream.StreamSource;
import org.xml.sax.InputSource;
import java.io.FileInputStream;

// Create and configure compiler
SchemaCompiler compiler = XJC.createSchemaCompiler();
compiler.setDefaultPackageName("com.example.generated");
compiler.setErrorListener(new MyErrorListener());

// Parse schema from file
InputSource source = new InputSource(new FileInputStream("schema.xsd"));
source.setSystemId("schema.xsd");
compiler.parseSchema(source);

// Parse additional schema from URL
compiler.parseSchema(new InputSource("http://example.com/common.xsd"));

// Compile schemas
S2JJAXBModel model = compiler.bind();
if (model != null) {
    // Generate code
    JCodeModel codeModel = model.generateCode(null, errorListener);
    codeModel.build(new FileCodeWriter(outputDir));
}

Compilation Result Model

Interface representing the result of schema-to-Java compilation.

/**
 * Schema-to-Java compilation result with code generation capabilities
 */
public interface S2JJAXBModel extends JAXBModel {
    /**
     * Get mapping information for a specific XML element
     * @param elementName QName of the XML element
     * @return Mapping information or null if not found
     */
    Mapping get(QName elementName);
    
    /**
     * Get all generated ObjectFactory classes
     * @return List of JClass representing ObjectFactory classes
     */
    List<JClass> getAllObjectFactories();
    
    /**
     * Get all XML-to-Java mappings
     * @return Collection of all mapping information
     */
    Collection<? extends Mapping> getMappings();
    
    /**
     * Get Java type information for XML type
     * @param xmlTypeName QName of the XML type
     * @return TypeAndAnnotation containing Java type info, or null if not found
     */
    TypeAndAnnotation getJavaType(QName xmlTypeName);
    
    /**
     * Generate Java source code with optional plugins
     * @param extensions Array of plugins to apply during generation
     * @param errorListener Listener for generation errors
     * @return JCodeModel containing generated classes
     * @throws IOException if code generation fails
     */
    JCodeModel generateCode(Plugin[] extensions, ErrorListener errorListener) throws IOException;
}

/**
 * Base interface for JAXB compilation models
 */
public interface JAXBModel {
    /**
     * Get list of generated class names
     * @return List of fully qualified class names
     * @deprecated Use S2JJAXBModel methods instead
     */
    @Deprecated
    List<String> getClassList();
}

Error Handling Interface

Interface for handling compilation errors, warnings, and informational messages.

/**
 * Error handling interface for programmatic API usage
 */
public interface ErrorListener {
    /**
     * Handle compilation errors
     * @param exception SAXParseException containing error details
     */
    void error(SAXParseException exception);
    
    /**
     * Handle compilation warnings
     * @param exception SAXParseException containing warning details
     */
    void warning(SAXParseException exception);
    
    /**
     * Handle informational messages
     * @param exception SAXParseException containing info details
     */
    void info(SAXParseException exception);
}

Usage Example:

import com.sun.tools.xjc.api.ErrorListener;
import org.xml.sax.SAXParseException;

ErrorListener errorListener = new ErrorListener() {
    @Override
    public void error(SAXParseException exception) {
        System.err.printf("Error at %s:%d:%d - %s%n",
            exception.getSystemId(),
            exception.getLineNumber(),
            exception.getColumnNumber(),
            exception.getMessage());
    }
    
    @Override
    public void warning(SAXParseException exception) {
        System.err.printf("Warning at %s:%d:%d - %s%n",
            exception.getSystemId(),
            exception.getLineNumber(),
            exception.getColumnNumber(),
            exception.getMessage());
    }
    
    @Override
    public void info(SAXParseException exception) {
        System.out.printf("Info: %s%n", exception.getMessage());
    }
};

API Utility Interfaces

Supporting interfaces for customizing compilation behavior.

/**
 * Custom class name allocation strategy for resolving conflicts
 */
public interface ClassNameAllocator {
    /**
     * Assign class name for given package and suggested name
     * @param packageName Package name for the class
     * @param className Suggested class name
     * @return Final class name to use (may be modified to avoid conflicts)
     */
    String assignClassName(String packageName, String className);
}

/**
 * Information about generated properties
 */
public interface Property {
    /**
     * Get property name
     * @return Property name in Java
     */
    String name();
    
    /**
     * Get Java type for the property
     * @return JType representing the Java type
     */
    JType type();
    
    /**
     * Get XML element name for the property
     * @return QName of the XML element
     */
    QName elementName();
    
    /**
     * Get raw XML name
     * @return QName of the raw XML name
     */
    QName rawName();
}

/**
 * Type information with annotations
 */
public interface TypeAndAnnotation {
    // Type and annotation information for generated classes
}

/**
 * XML to Java mapping information
 */
public interface Mapping {
    // Mapping details between XML schema and Java classes
}

/**
 * JAXB specification version enumeration
 */
public enum SpecVersion {
    V2_3("2.3"),
    V3_0("3.0");
    
    public final String version;
    
    SpecVersion(String version);
    public static SpecVersion parse(String token);
    public boolean isLaterThan(SpecVersion other);
}

Complete Integration Example

import com.sun.tools.xjc.api.*;
import com.sun.codemodel.*;
import com.sun.codemodel.writer.FileCodeWriter;
import org.xml.sax.InputSource;
import org.xml.sax.SAXParseException;
import javax.xml.namespace.QName;
import java.io.*;
import java.util.Collection;

public class XJCIntegration {
    
    public static void compileSchema(File schemaFile, File outputDir, String packageName) 
            throws IOException {
        
        // Create compiler with error handling
        SchemaCompiler compiler = XJC.createSchemaCompiler();
        ErrorCollector errorListener = new ErrorCollector();
        
        // Configure compiler
        compiler.setDefaultPackageName(packageName);
        compiler.setErrorListener(errorListener);
        
        // Custom class name allocator
        compiler.setClassNameAllocator(new ClassNameAllocator() {
            @Override
            public String assignClassName(String packageName, String className) {
                // Add "Generated" suffix to avoid conflicts
                return className + "Generated";
            }
        });
        
        // Parse schema
        InputSource source = new InputSource(new FileInputStream(schemaFile));
        source.setSystemId(schemaFile.toURI().toString());
        compiler.parseSchema(source);
        
        // Check for parsing errors
        if (errorListener.hasErrors()) {
            throw new IOException("Schema parsing failed with errors");
        }
        
        // Compile schema
        S2JJAXBModel model = compiler.bind();
        if (model == null) {
            throw new IOException("Schema compilation failed");
        }
        
        // Examine generated mappings
        Collection<? extends Mapping> mappings = model.getMappings();
        System.out.printf("Generated %d mappings%n", mappings.size());
        
        // Generate code
        JCodeModel codeModel = model.generateCode(null, errorListener);
        
        // Write to filesystem
        codeModel.build(new FileCodeWriter(outputDir));
        
        System.out.printf("Generated code in %s%n", outputDir.getAbsolutePath());
    }
    
    private static class ErrorCollector implements ErrorListener {
        private boolean hasErrors = false;
        
        @Override
        public void error(SAXParseException exception) {
            hasErrors = true;
            System.err.println("Error: " + exception.getMessage());
        }
        
        @Override
        public void warning(SAXParseException exception) {
            System.err.println("Warning: " + exception.getMessage());
        }
        
        @Override
        public void info(SAXParseException exception) {
            System.out.println("Info: " + exception.getMessage());
        }
        
        public boolean hasErrors() {
            return hasErrors;
        }
    }
}

Install with Tessl CLI

npx tessl i tessl/maven-org-glassfish-jaxb--jaxb-xjc

docs

build-integration.md

cli.md

code-generation.md

error-handling.md

index.md

plugin-system.md

programmatic-api.md

tile.json