Package org.jibx.schema.codegen
Class CodeGen
- java.lang.Object
-
- org.jibx.schema.codegen.CodeGen
-
public class CodeGen extends java.lang.ObjectCode generator from schema definition. Although many of the methods in this class usepublicaccess, 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 themain(String[])method with an appropriate argument list.- Author:
- Dennis M. Sosnoski
-
-
Nested Class Summary
Nested Classes Modifier and Type Class Description private static classCodeGen.SchemaNameVisitorVisitor for checking element namespace usage in schema definitions.private static classCodeGen.ValueCountVisitorVisitor to count the number of values in a definition.
-
Field Summary
Fields Modifier and Type Field Description private static longBLOCK_NAME_INHERIT_MASKMask for schema elements which block name inheritance downward.private static QName[]DEFAULT_REPLACEMENTSDefault type replacements applied.private BindingOrganizerm_bindingDirectoryDirectory for constructed bindings.private SchemasetCustomm_globalCode generation customizations.private PackageOrganizerm_packageDirectoryPackage directory for generated classes.private BindingHolderm_rootHolderRoot binding definition holder (set bywriteBindings(String, String, List, ProblemHandler)).private java.io.Filem_targetDirTarget directory for code generation.private ValidationContextm_validationContextContext for loading and processing schemas.private static Loggers_loggerLogger for class.private static longTYPE_DEFINE_MASKMask for schema elements which define a type.private static longTYPE_DERIVE_MASKMask for schema elements which derive from a type.
-
Constructor Summary
Constructors Constructor Description CodeGen(SchemasetCustom global, java.net.URL root, java.io.File target)Constructor.CodeGen(SchemasetCustom custom, ValidationContext vctx)Constructor used by tests.
-
Method Summary
All Methods Static Methods Instance Methods Concrete Methods Modifier and Type Method Description private static voidaccumulateBindingDefinitions(BindingElement binding, java.util.Map elemmap, java.util.Map typemap)Accumulate all format and mapping definitions, including those found in included bindings.private static voidaddDefaultSubstitutions(SchemasetCustom custom)Add default type substitutions to set currently defined.voidapplyAndNormalize()Apply extensions and normalize all schemas.private java.lang.StringassembleName(java.lang.String prefix, java.lang.String base)Assemble a name from a base name and an optional prefix.private voidassignNames(java.lang.String prefix, GroupItem group, boolean force)Set the basic names to be used for a structure of items.private static TypeDatabuildClassData(java.lang.String cname, boolean simple)Build class data for pregenerated class.private voidbuildClassesAndBindings(java.util.ArrayList defs, java.util.Map typeinst)Build classes and bindings for all definitions, except those for singleton element definitions using a type.java.lang.StringbuildDataModel(boolean verbose, boolean usenns, java.util.Map elemmap, java.util.Map typemap)Generate the data model.private java.util.ArrayListbuildItemStructures()Build the structure of items to be used in code generation for each global definition.private java.lang.StringcheckDirectName(Item item)Check if an item has an associated name.private voidcheckInline(DefinitionItem def, int depth, java.util.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 booleancheckNoNamespacedUsed()Check if no-namespace namespace is used in any of the schemas.private voidcompactGroups(GroupItem group)Compact group structures.private intcomputeComplexity(GroupItem group, int depth, java.util.List defs)Compute the complexity of a structure.private voidconvertToDefinitions(GroupItem group, java.util.List defs)Convert nested groups which are not inlined to freestanding definitions.private java.util.MapconvertTypeIsomorphicElements(java.util.ArrayList items)Convert the item model used for global elements, if they're the only reference to a global type.booleancustomizeSchemas(java.lang.String pack, ProblemHandler handler)Validate and apply customizations to loaded schemas.private java.lang.StringderiveName(Item item, boolean force)Derive the base name for an item.static java.util.ListfindPathSteps(java.io.File file)Find the steps in the canonical path to a file.SchemasetCustomfindSchemaset(SchemaElement schema, SchemasetCustom custom)Find the most specific schemaset owning a schema.booleangenerate(boolean verbose, java.lang.String usens, java.lang.String dfltpkg, java.lang.String bindname, java.util.List fileset, java.util.List inclpaths, java.io.File model, ProblemHandler handler)Generate code from a list of schemas.BindingOrganizergetBindingDirectory()Get the binding directory.PackageOrganizergetPackageDirectory()Get the package directory used for code generation.BindingElementgetRootBinding()Get the root binding definition.ValidationContextgetSchemaValidationContext()Get the validation context used for processing schemas.private voidinitializeBindings()Initialize the bindings to be generated.private java.util.ArrayListinlineReferences(java.util.ArrayList items)Build list of definitions to be generated.private booleanisSimple(GroupItem group)Check if a group consists only of a single non-repeating item, which is not an enumeration.private static voidlistGeneratedPackages(java.util.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 voidmain(java.lang.String[] args)Run the binding generation using command line parameters.private booleanprocessExtensions()Process substitutions and deletions defined by extensions.static BindingElementprocessPregeneratedBinding(java.net.URL url, java.util.Map elemmap, java.util.Map typemap, ProblemHandler handler)Load and validate binding and process all format and mapping definitions, including those in included bindings.voidpruneDefinitions()Processes the schemas to remove unused global definitions.static java.lang.StringrelativeFilePath(java.io.File dir, java.io.File file)Construct a relative file path.private static voidreportBindingProblems(ValidationContext vctx, ProblemHandler handler)Report problems found in binding.voidsetDefaultPrefixes(java.util.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(java.lang.String name, java.lang.String pack, java.util.List pregens, ProblemHandler handler)Write the binding definitions file(s).
-
-
-
Field Detail
-
s_logger
private static final Logger s_logger
Logger for class.
-
DEFAULT_REPLACEMENTS
private static final QName[] DEFAULT_REPLACEMENTS
Default type replacements applied.
-
TYPE_DERIVE_MASK
private static final long TYPE_DERIVE_MASK
Mask for schema elements which derive from a type.
-
TYPE_DEFINE_MASK
private static final long TYPE_DEFINE_MASK
Mask for schema elements which define a type.
-
BLOCK_NAME_INHERIT_MASK
private static final long BLOCK_NAME_INHERIT_MASK
Mask for schema elements which block name inheritance downward.
-
m_global
private final SchemasetCustom m_global
Code generation customizations.
-
m_targetDir
private final java.io.File m_targetDir
Target directory for code generation.
-
m_validationContext
private final ValidationContext m_validationContext
Context for loading and processing schemas.
-
m_packageDirectory
private PackageOrganizer m_packageDirectory
Package directory for generated classes.
-
m_bindingDirectory
private BindingOrganizer m_bindingDirectory
Directory for constructed bindings.
-
m_rootHolder
private BindingHolder m_rootHolder
Root binding definition holder (set bywriteBindings(String, String, List, ProblemHandler)).
-
-
Constructor Detail
-
CodeGen
public CodeGen(SchemasetCustom global, java.net.URL root, java.io.File target)
Constructor.- Parameters:
global- schema customization root elementroot- URL for base of schema pathstarget- destination directory for code generation
-
CodeGen
public CodeGen(SchemasetCustom custom, ValidationContext vctx)
Constructor used by tests. This uses supplied schemas and skips writing to the file system.- Parameters:
custom-vctx-
-
-
Method Detail
-
getSchemaValidationContext
public ValidationContext getSchemaValidationContext()
Get the validation context used for processing schemas.- Returns:
- context
-
addDefaultSubstitutions
private static void addDefaultSubstitutions(SchemasetCustom custom)
Add default type substitutions to set currently defined.- Parameters:
custom-
-
findSchemaset
public SchemasetCustom findSchemaset(SchemaElement schema, SchemasetCustom custom)
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
public void setDefaultPrefixes(java.util.Iterator iter)
Scan schemas to find the default prefixes used for namespaces.- Parameters:
iter- schema iterator
-
customizeSchemas
public boolean customizeSchemas(java.lang.String pack, ProblemHandler handler)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
private java.lang.String checkDirectName(Item item)
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
private java.lang.String deriveName(Item item, boolean force)
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
private void compactGroups(GroupItem group)
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
private java.lang.String assembleName(java.lang.String prefix, java.lang.String base)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
private void assignNames(java.lang.String prefix, GroupItem group, boolean force)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
private int computeComplexity(GroupItem group, int depth, java.util.List defs)
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
private boolean isSimple(GroupItem group)
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
private void convertToDefinitions(GroupItem group, java.util.List defs)
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
private void checkInline(DefinitionItem def, int depth, java.util.List defs)
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
private void setName(QName qname, MappingElementBase mapping, BindingHolder holder)
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
private java.util.ArrayList buildItemStructures()
Build the structure of items to be used in code generation for each global definition.- Returns:
- constructed definition items
-
convertTypeIsomorphicElements
private java.util.Map convertTypeIsomorphicElements(java.util.ArrayList items)
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
private java.util.ArrayList inlineReferences(java.util.ArrayList items)
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
private void buildClassesAndBindings(java.util.ArrayList defs, java.util.Map typeinst)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
public java.lang.String buildDataModel(boolean verbose, boolean usenns, java.util.Map elemmap, java.util.Map typemap)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 flagtypemap- map from qualified name of type (or attributeGroup, or group) to pregenerated mapping definitionelemmap- map from qualified name of element to pregenerated mapping definition- Returns:
- root package for binding
-
getBindingDirectory
public BindingOrganizer getBindingDirectory()
Get the binding directory.- Returns:
- directory
-
writeBindings
public void writeBindings(java.lang.String name, java.lang.String pack, java.util.List pregens, ProblemHandler handler) throws JiBXException, java.io.IOExceptionWrite 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:
JiBXExceptionjava.io.IOException
-
getRootBinding
public BindingElement getRootBinding()
Get the root binding definition. This is only allowed after the call towriteBindings(String, String, List, ProblemHandler).- Returns:
- root binding element
-
getPackageDirectory
public PackageOrganizer getPackageDirectory()
Get the package directory used for code generation.- Returns:
- directory
-
generate
public boolean generate(boolean verbose, java.lang.String usens, java.lang.String dfltpkg, java.lang.String bindname, java.util.List fileset, java.util.List inclpaths, java.io.File model, ProblemHandler handler) throws JiBXException, java.io.IOExceptionGenerate 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:
JiBXExceptionjava.io.IOException
-
listSchemas
private static void listSchemas(SchemaElement[] schemas, ValidationContext vctx, ProblemHandler handler)
List the schemas in use.- Parameters:
schemas-vctx-handler-
-
listGeneratedPackages
private static void listGeneratedPackages(java.util.List packages, ProblemHandler handler)List the number of classes in each package, and the totals.- Parameters:
packages-handler-
-
buildClassData
private static TypeData buildClassData(java.lang.String cname, boolean simple)
Build class data for pregenerated class.- Parameters:
cname- class namesimple- simple value flag- Returns:
- data
-
accumulateBindingDefinitions
private static void accumulateBindingDefinitions(BindingElement binding, java.util.Map elemmap, java.util.Map typemap)
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(java.net.URL url, java.util.Map elemmap, java.util.Map typemap, ProblemHandler handler) throws JiBXException, java.io.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:
JiBXExceptionjava.io.IOException
-
reportBindingProblems
private static void reportBindingProblems(ValidationContext vctx, ProblemHandler handler)
Report problems found in binding.- Parameters:
vctx-handler-
-
findPathSteps
public static java.util.List findPathSteps(java.io.File file) throws java.io.IOExceptionFind the steps in the canonical path to a file.- Parameters:
file-- Returns:
- steps
- Throws:
java.io.IOException
-
relativeFilePath
public static java.lang.String relativeFilePath(java.io.File dir, java.io.File file) throws java.io.IOExceptionConstruct a relative file path.- Parameters:
dir- start directory for pathfile- supplied file path- Returns:
- relative file path
- Throws:
java.io.IOException
-
checkNoNamespace
public static boolean checkNoNamespace(BindingElement binding)
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
public static void main(java.lang.String[] args) throws java.lang.ExceptionRun the binding generation using command line parameters.- Parameters:
args-- Throws:
java.lang.Exception
-
-