Package org.jibx.schema.codegen
Class CodeGen
java.lang.Object
org.jibx.schema.codegen.CodeGen
Code generator from schema definition. Although many of the methods in this class use
public access,
they are intended for use only by the JiBX developers and may change from one release to the next. To make use of
this class from your own code, call the main(String[]) method with an appropriate argument list.- Author:
- Dennis M. Sosnoski
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionprivate static classVisitor for checking element namespace usage in schema definitions.private static classVisitor to count the number of values in a definition. -
Field Summary
FieldsModifier and TypeFieldDescriptionprivate static final longMask for schema elements which block name inheritance downward.private static final QName[]Default type replacements applied.private BindingOrganizerDirectory for constructed bindings.private final SchemasetCustomCode generation customizations.private PackageOrganizerPackage directory for generated classes.private BindingHolderRoot binding definition holder (set bywriteBindings(String, String, List, ProblemHandler)).private final FileTarget directory for code generation.private final ValidationContextContext for loading and processing schemas.private static final LoggerLogger for class.private static final longMask for schema elements which define a type.private static final longMask for schema elements which derive from a type. -
Constructor Summary
ConstructorsConstructorDescriptionCodeGen(SchemasetCustom global, URL root, File target) Constructor.CodeGen(SchemasetCustom custom, ValidationContext vctx) Constructor used by tests. -
Method Summary
Modifier and TypeMethodDescriptionprivate static voidaccumulateBindingDefinitions(BindingElement binding, Map elemmap, Map typemap) Accumulate all format and mapping definitions, including those found in included bindings.private static voidAdd default type substitutions to set currently defined.voidApply extensions and normalize all schemas.private StringassembleName(String prefix, String base) Assemble a name from a base name and an optional prefix.private voidassignNames(String prefix, GroupItem group, boolean force) Set the basic names to be used for a structure of items.private static TypeDatabuildClassData(String cname, boolean simple) Build class data for pregenerated class.private voidbuildClassesAndBindings(ArrayList defs, Map typeinst) Build classes and bindings for all definitions, except those for singleton element definitions using a type.buildDataModel(boolean verbose, boolean usenns, Map elemmap, Map typemap) Generate the data model.private ArrayListBuild the structure of items to be used in code generation for each global definition.private StringcheckDirectName(Item item) Check if an item has an associated name.private voidcheckInline(DefinitionItem def, int depth, List defs) Check if a global definition structure is to be inlined.static booleancheckNoNamespace(BindingElement binding) Check if a binding definition uses the no-namespace namespace.private booleanCheck if no-namespace namespace is used in any of the schemas.private voidcompactGroups(GroupItem group) Compact group structures.private intcomputeComplexity(GroupItem group, int depth, List defs) Compute the complexity of a structure.private voidconvertToDefinitions(GroupItem group, List defs) Convert nested groups which are not inlined to freestanding definitions.private MapConvert the item model used for global elements, if they're the only reference to a global type.booleancustomizeSchemas(String pack, ProblemHandler handler) Validate and apply customizations to loaded schemas.private StringderiveName(Item item, boolean force) Derive the base name for an item.static ListfindPathSteps(File file) Find the steps in the canonical path to a file.findSchemaset(SchemaElement schema, SchemasetCustom custom) Find the most specific schemaset owning a schema.booleangenerate(boolean verbose, String usens, String dfltpkg, String bindname, List fileset, List inclpaths, File model, ProblemHandler handler) Generate code from a list of schemas.Get the binding directory.Get the package directory used for code generation.Get the root binding definition.Get the validation context used for processing schemas.private voidInitialize the bindings to be generated.private ArrayListinlineReferences(ArrayList items) Build list of definitions to be generated.private booleanCheck if a group consists only of a single non-repeating item, which is not an enumeration.private static voidlistGeneratedPackages(List packages, ProblemHandler handler) List the number of classes in each package, and the totals.private static voidlistSchemas(SchemaElement[] schemas, ValidationContext vctx, ProblemHandler handler) List the schemas in use.static voidRun the binding generation using command line parameters.private booleanProcess substitutions and deletions defined by extensions.static BindingElementprocessPregeneratedBinding(URL url, Map elemmap, Map typemap, ProblemHandler handler) Load and validate binding and process all format and mapping definitions, including those in included bindings.voidProcesses the schemas to remove unused global definitions.static StringrelativeFilePath(File dir, File file) Construct a relative file path.private static voidreportBindingProblems(ValidationContext vctx, ProblemHandler handler) Report problems found in binding.voidsetDefaultPrefixes(Iterator iter) Scan schemas to find the default prefixes used for namespaces.private voidsetName(QName qname, MappingElementBase mapping, BindingHolder holder) Set the name and namespace URI for a concrete <mapping> binding component.voidwriteBindings(String name, String pack, List pregens, ProblemHandler handler) Write the binding definitions file(s).
-
Field Details
-
s_logger
private static final Logger s_loggerLogger for class. -
DEFAULT_REPLACEMENTS
Default type replacements applied. -
TYPE_DERIVE_MASK
private static final long TYPE_DERIVE_MASKMask for schema elements which derive from a type. -
TYPE_DEFINE_MASK
private static final long TYPE_DEFINE_MASKMask for schema elements which define a type. -
BLOCK_NAME_INHERIT_MASK
private static final long BLOCK_NAME_INHERIT_MASKMask for schema elements which block name inheritance downward. -
m_global
Code generation customizations. -
m_targetDir
Target directory for code generation. -
m_validationContext
Context for loading and processing schemas. -
m_packageDirectory
Package directory for generated classes. -
m_bindingDirectory
Directory for constructed bindings. -
m_rootHolder
Root binding definition holder (set bywriteBindings(String, String, List, ProblemHandler)).
-
-
Constructor Details
-
CodeGen
Constructor.- Parameters:
global- schema customization root elementroot- URL for base of schema pathstarget- destination directory for code generation
-
CodeGen
Constructor used by tests. This uses supplied schemas and skips writing to the file system.- Parameters:
custom-vctx-
-
-
Method Details
-
getSchemaValidationContext
Get the validation context used for processing schemas.- Returns:
- context
-
addDefaultSubstitutions
Add default type substitutions to set currently defined.- Parameters:
custom-
-
findSchemaset
Find the most specific schemaset owning a schema. If multiple matches are found which are not in line of containment the first match is returned and the conflict is reported as an error.- Parameters:
schema-custom- schema set customization- Returns:
- owning schemaset,
nullif none
-
setDefaultPrefixes
Scan schemas to find the default prefixes used for namespaces.- Parameters:
iter- schema iterator
-
customizeSchemas
Validate and apply customizations to loaded schemas.- Parameters:
pack- package to be used by default for no-namespaced schemas (non-null)handler- validation problem handler- Returns:
trueif successful,falseif error
-
processExtensions
private boolean processExtensions()Process substitutions and deletions defined by extensions. This builds the cross-reference information for the global definition components of the schemas while removing references to deleted components.- Returns:
trueif any changes to the schemas,falseif not
-
applyAndNormalize
public void applyAndNormalize()Apply extensions and normalize all schemas. This may be a multipass process, since applying extensions may create the opportunity for further normalizations and vice versa. -
pruneDefinitions
public void pruneDefinitions()Processes the schemas to remove unused global definitions. -
checkDirectName
Check if an item has an associated name. If the component associated with the item has a name, this just returns that name converted to base name form. The only exception is for inlined global type definitions, which are treated as unnamed.- Parameters:
item-- Returns:
- name associated name, or
nullif none
-
deriveName
Derive the base name for an item. If not forced, the only time a name will be returned is when the item is a reference to a non-type definition. If forced, this will try other alternatives for names including the text "Enumeration" for an enumeration group, the base type name for a type derivation, the schema type name for a value of a schema type, or finally the schema component element name.- Parameters:
item-force- name forced flag- Returns:
- name (
nullif to use inherited name whenforce == false)
-
compactGroups
Compact group structures. This eliminates redundant groupings, in the form of groups with only one child, which child is a group referencing the same schema component as the parent group, from the data structure representation.- Parameters:
group-
-
assembleName
Assemble a name from a base name and an optional prefix. If the prefix is supplied, this first converts the base name to embedded form, then appends the prefix.- Parameters:
prefix-base-- Returns:
- name
-
assignNames
Set the basic names to be used for a structure of items. For named components of the schema definition the names used are simply the converted XML local names, for other components more complex rules apply (seederiveName(Item,boolean). This method calls itself recursively to handle nested groups.- Parameters:
prefix- text to be prefixed to names within inlined group (nullif none)group- item group to be assignedforce- force name derivation flag
-
computeComplexity
Compute the complexity of a structure. In order to find the complexity of a structure all items of the structure must first be checked for inlining, which in turn requires checking their complexity. That makes this method mutually recursive withcheckInline(DefinitionItem, int, List).- Parameters:
group-depth- nesting depthdefs- list of generated definitions- Returns:
- complexity (0, 1, or 2 for anything more than a single value)
-
isSimple
Check if a group consists only of a single non-repeating item, which is not an enumeration.- Parameters:
group-- Returns:
trueif simple group,falseif repeated, multiple, or enumeration
-
convertToDefinitions
Convert nested groups which are not inlined to freestanding definitions. This calls itself recursively to process nested groups, except those nested within groups converted to definitions.- Parameters:
group-defs- list of generated definitions
-
checkInline
Check if a global definition structure is to be inlined. This method is mutually recursive withcomputeComplexity(GroupItem, int, List). The two methods together determine the inlining status of all items.- Parameters:
def-depth- nesting depthdefs- list of generated definitions
-
setName
Set the name and namespace URI for a concrete <mapping> binding component. This is the same logic as used in theStructureClassHolderequivalent.- Parameters:
qname- qualified name to be set (nullif none)mapping- concrete mapping definitionholder- binding containing the mapping
-
buildItemStructures
Build the structure of items to be used in code generation for each global definition.- Returns:
- constructed definition items
-
convertTypeIsomorphicElements
Convert the item model used for global elements, if they're the only reference to a global type. This just prevents generating two separate classes, one for the type and one for the element.- Parameters:
items- global definition items- Returns:
- map from base type definition to singleton element definition using that type
-
inlineReferences
Build list of definitions to be generated. Where possible, references are converted to inline definitions. Where they can't be converted, new definitions are created for separate class generation.- Parameters:
items-- Returns:
- definitions to be processed
-
checkNoNamespacedUsed
private boolean checkNoNamespacedUsed()Check if no-namespace namespace is used in any of the schemas.- Returns:
trueif no-namespace used,falseif not
-
buildClassesAndBindings
Build classes and bindings for all definitions, except those for singleton element definitions using a type.- Parameters:
defs- definitions to be generatedtypeinst- map from base type definition to singleton element definition using that type
-
initializeBindings
private void initializeBindings()Initialize the bindings to be generated. This configures the binding directory, then creates the required bindings and sets their prefixes. -
buildDataModel
Generate the data model. This first builds a representation of all the data items from the schema definitions, then determines which items can be inlined and which need separate class representations, and finally builds the actual data model class and binding definitions.- Parameters:
verbose- verbose output flagusenns- no-namespace namespace used flagelemmap- map from qualified name of element to pregenerated mapping definitiontypemap- map from qualified name of type (or attributeGroup, or group) to pregenerated mapping definition- Returns:
- root package for binding
-
getBindingDirectory
Get the binding directory.- Returns:
- directory
-
writeBindings
public void writeBindings(String name, String pack, List pregens, ProblemHandler handler) throws JiBXException, IOException Write the binding definitions file(s). This method can only be used afterbuildDataModel(boolean, boolean, Map, Map)is called.- Parameters:
name- root binding definition file name (use customization, or default, ifnull)pack- target package for binding (nullif unspecified)pregens- pregenerated bindings to be included in root bindinghandler- validation error and code generation problem handler- Throws:
JiBXExceptionIOException
-
getRootBinding
Get the root binding definition. This is only allowed after the call towriteBindings(String, String, List, ProblemHandler).- Returns:
- root binding element
-
getPackageDirectory
Get the package directory used for code generation.- Returns:
- directory
-
generate
public boolean generate(boolean verbose, String usens, String dfltpkg, String bindname, List fileset, List inclpaths, File model, ProblemHandler handler) throws JiBXException, IOException Generate code from a list of schemas.- Parameters:
verbose- verbose output flagusens- namespace to be used when no schemas with namespaces are being generated (nullif not specified)dfltpkg- default package for no-namespace schemas (nullif not specified)bindname- name for root binding (nullif not specified)fileset- list of resolvers for schemas to be generatedinclpaths- list of paths for bindings to be used for matching schema definitions (empty if none)model- file to be used for dumping generated data model (nullif none)handler- validation error and code generation problem handler- Returns:
trueif successful,falseif failure- Throws:
JiBXExceptionIOException
-
listSchemas
private static void listSchemas(SchemaElement[] schemas, ValidationContext vctx, ProblemHandler handler) List the schemas in use.- Parameters:
schemas-vctx-handler-
-
listGeneratedPackages
List the number of classes in each package, and the totals.- Parameters:
packages-handler-
-
buildClassData
Build class data for pregenerated class.- Parameters:
cname- class namesimple- simple value flag- Returns:
- data
-
accumulateBindingDefinitions
Accumulate all format and mapping definitions, including those found in included bindings. For each abstract mapping or named format found, the type name is associated with the class data in the type map; for each concrete mapping found, the element name (and namespace) is associated with the class data in the element map. Included bindings are handled with recursive calls.- Parameters:
binding- binding definition rootelemmap- map from element qualified name to class datatypemap- map from type qualified name to class data
-
processPregeneratedBinding
public static BindingElement processPregeneratedBinding(URL url, Map elemmap, Map typemap, ProblemHandler handler) throws JiBXException, IOException Load and validate binding and process all format and mapping definitions, including those in included bindings.- Parameters:
url- binding definition pathelemmap- map from element qualified name to class datatypemap- map from type qualified name to class datahandler- validation error and problem handler- Returns:
- binding
- Throws:
JiBXExceptionIOException
-
reportBindingProblems
Report problems found in binding.- Parameters:
vctx-handler-
-
findPathSteps
Find the steps in the canonical path to a file.- Parameters:
file-- Returns:
- steps
- Throws:
IOException
-
relativeFilePath
Construct a relative file path.- Parameters:
dir- start directory for pathfile- supplied file path- Returns:
- relative file path
- Throws:
IOException
-
checkNoNamespace
Check if a binding definition uses the no-namespace namespace. This calls itself to recursively check on included bindings.- Parameters:
binding-- Returns:
trueif no-namespace namespace used,falseif not
-
main
Run the binding generation using command line parameters.- Parameters:
args-- Throws:
Exception
-