Content
field.]]>
public void setVersion(String version)
{
this.currentVersion = version;
}
public String getVersion()
{
return currentVersion;
}
private String packageName;
public void setPackage(String packageName)
{
this.packageName = packageName;
}
public String getPackage()
{
return packageName;
}
public String getId()
{
StringBuffer id = new StringBuffer();
id.append( getGroupId() );
id.append( ":" );
id.append( getArtifactId() );
id.append( ":" );
id.append( getType() );
id.append( ":" );
id.append( getVersion() );
return id.toString();
}
public String getId()
{
return groupId + ":" + artifactId + ":" + type + ":" + version;
}
public String toString()
{
return groupId + "/" + type + "s:" + artifactId + "-" + version;
}
element is explicity used in the POM.
if ( getJar() != null)
{
return getJar();
}
return getArtifactId() + "-" + getVersion() + "." + getExtension();
}
public String getExtension()
{
if ("ejb".equals(getType()) || "plugin".equals(getType()) || "aspect".equals(getType())) return "jar";
return getType();
}
public boolean isAddedToClasspath()
{
return ("jar".equals(getType()) || "ejb".equals(getType()));
}
public boolean isPlugin()
{
return ("plugin".equals(getType()));
}
public String getProperty( String property )
{
return getProperties().getProperty( property );
}
public boolean equals( Object o )
{
if ( o == null )
{
return false;
}
if ( getClass() != o.getClass() )
{
return false;
}
if ( getId() != null )
{
return getId().equals( ( (Dependency) o ).getId() );
}
else
{
return ( (Dependency) o ).getId() == null;
}
}
public int hashCode()
{
if ( getId() != null )
{
return getId().hashCode();
}
else
{
return super.hashCode();
}
}
]]>
public java.util.List getDefaultExcludes()
{
java.util.List defaultExcludes = new java.util.ArrayList();
defaultExcludes.add( "**/*~" );
defaultExcludes.add( "**/#*#" );
defaultExcludes.add( "**/.#*" );
defaultExcludes.add( "**/%*%" );
defaultExcludes.add( "**/._*" );
// CVS
defaultExcludes.add( "**/CVS" );
defaultExcludes.add( "**/CVS/**" );
defaultExcludes.add( "**/.cvsignore" );
// SCCS
defaultExcludes.add( "**/SCCS" );
defaultExcludes.add( "**/SCCS/**" );
// Visual SourceSafe
defaultExcludes.add( "**/vssver.scc" );
// Subversion
defaultExcludes.add( "**/.svn" );
defaultExcludes.add( "**/.svn/**" );
// Mac
defaultExcludes.add( "**/.DS_Store" );
return defaultExcludes;
}
public boolean isFiltering()
{
return !"false".equals( filtering );
}
public void setFiltering( boolean filtering )
{
this.filtering = ( filtering ? "true" : "false" );
}
public boolean equals( Object obj )
{
Repository other = ( Repository ) obj;
boolean retValue = false;
if ( id != null )
{
retValue = id.equals( other.id );
}
return retValue;
}
Modello StAX Plugin generates XML readers and writers based on StAX API, plus reader delegates to be able to read multiple model versions.
stax-reader
generator creates
my.model.package.io.stax.ModelNameStaxReader
class with following
public methods:
public RootClass ( Reader reader, boolean strict )
throws IOException, XMLStreamException
public RootClass read( Reader reader )
throws IOException, XMLStreamException
public RootClass read( String filePath, boolean strict )
throws IOException, XMLStreamException
public RootClass read( String filePath )
throws IOException, XMLStreamException
In addition, if multiple model reader versions are generated (each in its own package), it creates a delegate
my.model.package.io.xpp3.ModelNameStaxReaderDelegate
class with
following public methods:
public Object read( File f, boolean strict )
throws IOException, XMLStreamException
public Object read( File f )
throws IOException, XMLStreamException
Depending on the model version found in the XML content, the returned Object
will be of the right
version package.
stax-writer
generator creates
my.model.package.io.stax.ModelNameStaxWriter
class with following
public methods:
public void write( Writer writer, RootClass root )
throws IOException, XMLStreamException
ModelNameStaxReader
class in io.stax
sub-package
* with public RootClass read( ... )
methods.
*
* @throws ModelloException
* @throws IOException
*/
private void generateStaxReader()
throws ModelloException, IOException
{
Model objectModel = getModel();
String packageName = objectModel.getDefaultPackageName( isPackageWithVersion(), getGeneratedVersion() )
+ ".io.stax";
String unmarshallerName = getFileName( "StaxReader" );
JSourceWriter sourceWriter = newJSourceWriter( packageName, unmarshallerName );
JClass jClass = new JClass( packageName + '.' + unmarshallerName );
initHeader( jClass );
suppressAllWarnings( objectModel, jClass );
jClass.addImport( "java.io.IOException" );
jClass.addImport( "java.io.Reader" );
jClass.addImport( "java.io.File" );
jClass.addImport( "java.io.FileInputStream" );
jClass.addImport( "java.io.StringWriter" );
jClass.addImport( "java.io.StringReader" );
jClass.addImport( "java.io.ByteArrayInputStream" );
jClass.addImport( "java.io.InputStreamReader" );
jClass.addImport( "java.text.DateFormat" );
jClass.addImport( "java.text.ParsePosition" );
jClass.addImport( "java.util.regex.Matcher" );
jClass.addImport( "java.util.regex.Pattern" );
jClass.addImport( "java.util.Locale" );
jClass.addImport( "javax.xml.stream.*" );
jClass.addImport( "org.codehaus.plexus.util.xml.Xpp3Dom" );
addModelImports( jClass, null );
// ----------------------------------------------------------------------
// Write the parse method which will do the unmarshalling.
// ----------------------------------------------------------------------
ModelClass root = objectModel.getClass( objectModel.getRoot( getGeneratedVersion() ), getGeneratedVersion() );
GeneratorNode rootNode = findRequiredReferenceResolvers( root, null );
writeReferenceResolvers( rootNode, jClass );
for ( Iterator i = rootNode.getNodesWithReferencableChildren().values().iterator(); i.hasNext(); )
{
GeneratorNode node = (GeneratorNode) i.next();
writeReferenceResolvers( node, jClass );
}
JClass returnType = new JClass( root.getName() );
JMethod method = new JMethod( "read", returnType, null );
method.addParameter( new JParameter( new JClass( "Reader" ), "reader" ) );
method.addParameter( new JParameter( JType.BOOLEAN, "strict" ) );
method.addException( new JClass( "IOException" ) );
method.addException( new JClass( "XMLStreamException" ) );
JSourceCode sc = method.getSourceCode();
sc.add( "XMLStreamReader xmlStreamReader = XMLInputFactory.newInstance().createXMLStreamReader( reader );" );
sc.add( "" );
sc.add( "String encoding = xmlStreamReader.getCharacterEncodingScheme();" );
sc.add( returnType + " value = parse" + root.getName() + "( \"" + resolveTagName( root )
+ "\", xmlStreamReader, strict, encoding );" );
sc.add( "resolveReferences( value );" );
sc.add( "return value;" );
jClass.addMethod( method );
// ----------------------------------------------------------------------
method = new JMethod( "read", returnType, null );
method.addParameter( new JParameter( new JClass( "Reader" ), "reader" ) );
method.addException( new JClass( "IOException" ) );
method.addException( new JClass( "XMLStreamException" ) );
sc = method.getSourceCode();
sc.add( "return read( reader, true );" );
jClass.addMethod( method );
// ----------------------------------------------------------------------
method = new JMethod( "read", returnType, null );
method.addParameter( new JParameter( new JClass( "String" ), "filePath" ) );
method.addParameter( new JParameter( JType.BOOLEAN, "strict" ) );
method.addException( new JClass( "IOException" ) );
method.addException( new JClass( "XMLStreamException" ) );
sc = method.getSourceCode();
sc.add( "File file = new File(filePath);" );
sc.add( "XMLStreamReader xmlStreamReader = XMLInputFactory.newInstance().createXMLStreamReader( "
+ "file.toURL().toExternalForm(), new FileInputStream(file) );" );
sc.add( "" );
sc.add( "String encoding = xmlStreamReader.getCharacterEncodingScheme();" );
sc.add( returnType + " value = parse" + root.getName() + "( \"" + resolveTagName( root )
+ "\", xmlStreamReader, strict, encoding );" );
sc.add( "resolveReferences( value );" );
sc.add( "return value;" );
jClass.addMethod( method );
// ----------------------------------------------------------------------
method = new JMethod( "read", returnType, null );
method.addParameter( new JParameter( new JClass( "String" ), "filePath" ) );
method.addException( new JClass( "IOException" ) );
method.addException( new JClass( "XMLStreamException" ) );
sc = method.getSourceCode();
sc.add( "return read( filePath, true );" );
jClass.addMethod( method );
// Determine the version. Currently, it causes the document to be reparsed, but could be made more efficient in
// future by buffering the read XML and piping that into any consequent read method.
VersionDefinition versionDefinition = objectModel.getVersionDefinition();
if ( versionDefinition != null )
{
writeDetermineVersionMethod( jClass, objectModel );
}
// ----------------------------------------------------------------------
// Write the class parsers
// ----------------------------------------------------------------------
writeAllClassesParser( objectModel, jClass );
// ----------------------------------------------------------------------
// Write helpers
// ----------------------------------------------------------------------
writeHelpers( jClass );
writeBuildDomMethod( jClass );
// ----------------------------------------------------------------------
//
// ----------------------------------------------------------------------
jClass.print( sourceWriter );
sourceWriter.close();
}
private void generateStaxReaderDelegate( List/*private ClassName parseClassName( ... )
method to parse a class from a model.
*
* @param modelClass the model class
* @param jClass the generated class source file
* @param rootElement is this class the root from the model?
* @throws ModelloException
*/
private void writeClassParser( ModelClass modelClass, JClass jClass, boolean rootElement )
throws ModelloException
{
String className = modelClass.getName();
String capClassName = capitalise( className );
String uncapClassName = uncapitalise( className );
JMethod unmarshall = new JMethod( "parse" + capClassName, new JClass( className ), null );
unmarshall.getModifiers().makePrivate();
unmarshall.addParameter( new JParameter( new JClass( "String" ), "tagName" ) );
unmarshall.addParameter( new JParameter( new JClass( "XMLStreamReader" ), "xmlStreamReader" ) );
unmarshall.addParameter( new JParameter( JType.BOOLEAN, "strict" ) );
unmarshall.addParameter( new JParameter( new JClass( "String" ), "encoding" ) );
unmarshall.addException( new JClass( "IOException" ) );
unmarshall.addException( new JClass( "XMLStreamException" ) );
JSourceCode sc = unmarshall.getSourceCode();
sc.add( className + ' ' + uncapClassName + " = new " + className + "();" );
ModelField contentField = getContentField( modelClass.getAllFields( getGeneratedVersion(), true ) );
if ( contentField != null )
{
writeAttributes( modelClass, uncapClassName, sc );
writePrimitiveField( contentField, contentField.getType(), uncapClassName,
"set" + capitalise( contentField.getName() ), sc );
}
else
{
sc.add( "java.util.Set parsed = new java.util.HashSet();" );
String instanceFieldName = getInstanceFieldName( className );
if ( rootElement )
{
// encoding parameter is only used in root class
sc.add( uncapClassName + ".setModelEncoding( encoding );" );
sc.add( "boolean foundRoot = false;" );
sc.add( "while ( xmlStreamReader.hasNext() )" );
sc.add( "{" );
sc.indent();
sc.add( "int eventType = xmlStreamReader.next();" );
sc.add( "if ( eventType == XMLStreamConstants.START_ELEMENT )" );
}
else
{
writeAttributes( modelClass, uncapClassName, sc );
if ( isAssociationPartToClass( modelClass ) )
{
jClass.addField( new JField( new JType( "java.util.Map" ), instanceFieldName ) );
sc.add( "if ( " + instanceFieldName + " == null )" );
sc.add( "{" );
sc.addIndented( instanceFieldName + " = new java.util.HashMap();" );
sc.add( "}" );
sc.add( "String v = xmlStreamReader.getAttributeValue( null, \"modello.id\" );" );
sc.add( "if ( v != null )" );
sc.add( "{" );
sc.addIndented( instanceFieldName + ".put( v, " + uncapClassName + " );" );
sc.add( "}" );
}
sc.add( "while ( xmlStreamReader.nextTag() == XMLStreamConstants.START_ELEMENT )" );
}
sc.add( "{" );
sc.indent();
boolean addElse = false;
if ( rootElement )
{
sc.add( "if ( xmlStreamReader.getLocalName().equals( tagName ) )" );
sc.add( "{" );
sc.indent();
VersionDefinition versionDefinition = modelClass.getModel().getVersionDefinition();
if ( versionDefinition != null && "namespace".equals( versionDefinition.getType() ) )
{
sc.add( "String modelVersion = getVersionFromRootNamespace( xmlStreamReader );" );
writeModelVersionCheck( sc );
}
writeAttributes( modelClass, uncapClassName, sc );
sc.add( "foundRoot = true;" );
sc.unindent();
sc.add( "}" );
addElse = true;
}
// Write other fields
for ( Iterator i = modelClass.getAllFields( getGeneratedVersion(), true ).iterator(); i.hasNext(); )
{
ModelField field = (ModelField) i.next();
XmlFieldMetadata xmlFieldMetadata = (XmlFieldMetadata) field.getMetadata( XmlFieldMetadata.ID );
if ( !xmlFieldMetadata.isAttribute() && !xmlFieldMetadata.isTransient() )
{
processField( field, xmlFieldMetadata, addElse, sc, uncapClassName, rootElement, jClass );
addElse = true;
}
}
if ( !rootElement )
{
/*
if ( modelClass.getFields( getGeneratedVersion() ).size() > 0 )
{
sc.add( "else" );
sc.add( "{" );
sc.addIndented( "parser.nextText();" );
sc.add( "}" );
}
*/
if ( addElse )
{
sc.add( "else" );
sc.add( "{" );
sc.indent();
}
sc.add( "if ( strict )" );
sc.add( "{" );
sc.addIndented( "throw new XMLStreamException( \"Unrecognised tag: '\" + xmlStreamReader.getLocalName() + "
+ "\"'\", xmlStreamReader.getLocation() );" );
sc.add( "}" );
sc.add( "else" );
sc.add( "{" );
sc.indent();
sc.add( "int unrecognizedTagCount = 1;" );
sc.add( "while( unrecognizedTagCount != 0 )" );
sc.add( "{" );
sc.indent();
sc.add( "xmlStreamReader.next();" );
sc.add( "if ( xmlStreamReader.getEventType() == XMLStreamConstants.START_ELEMENT )" );
sc.add( "{" );
sc.addIndented( "unrecognizedTagCount++;" );
sc.add( "}" );
sc.add( "else if ( xmlStreamReader.getEventType() == XMLStreamConstants.END_ELEMENT )" );
sc.add( "{" );
sc.addIndented( "unrecognizedTagCount--;" );
sc.add( "}" );
sc.unindent();
sc.add( "}" );
sc.unindent();
sc.add( "}" );
if ( addElse )
{
sc.unindent();
sc.add( "}" );
}
}
else
{ // rootElement == true
sc.add( "else" );
sc.add( "{" );
sc.indent();
sc.add( "if ( foundRoot )" );
sc.add( "{" );
sc.indent();
sc.add( "if ( strict )" );
sc.add( "{" );
sc.addIndented( "throw new XMLStreamException( \"Unrecognised tag: '\" + xmlStreamReader.getLocalName() + "
+ "\"'\", xmlStreamReader.getLocation() );" );
sc.add( "}" );
sc.unindent();
sc.add( "}" );
sc.unindent();
sc.add( "}" );
sc.unindent();
sc.add( "}" );
}
sc.unindent();
sc.add( "}" );
// This must be last so that we guarantee the ID has been filled already
if ( isAssociationPartToClass( modelClass ) )
{
List identifierFields = modelClass.getIdentifierFields( getGeneratedVersion() );
if ( identifierFields.size() == 1 )
{
ModelField field = (ModelField) identifierFields.get( 0 );
String v = uncapClassName + ".get" + capitalise( field.getName() ) + "()";
v = getValue( field.getType(), v, (XmlFieldMetadata) field.getMetadata( XmlFieldMetadata.ID ) );
sc.add( instanceFieldName + ".put( " + v + ", " + uncapClassName + " );" );
}
}
}
sc.add( "return " + uncapClassName + ";" );
jClass.addMethod( unmarshall );
}
private GeneratorNode findRequiredReferenceResolvers( ModelClass modelClass, GeneratorNode parent )
throws ModelloException
{
String className = modelClass.getName();
GeneratorNode value = new GeneratorNode( className, parent );
for ( Iterator i = modelClass.getAllFields( getGeneratedVersion(), true ).iterator(); i.hasNext(); )
{
ModelField field = (ModelField) i.next();
if ( field instanceof ModelAssociation )
{
ModelAssociation association = (ModelAssociation) field;
if ( isClassInModel( association.getTo(), getModel() ) )
{
ModelField referenceIdentifierField = getReferenceIdentifierField( association );
GeneratorNode child = null;
if ( referenceIdentifierField != null )
{
child = new GeneratorNode( association, parent );
child.setReferencable( true );
}
else
{
if ( !value.getChain().contains( association.getTo() ) )
{
// descend into child
child = findRequiredReferenceResolvers( association.getToClass(), value );
child.setAssociation( association );
}
}
if ( child != null )
{
value.addChild( child );
}
}
}
}
// propagate the flag up
for ( Iterator i = value.getChildren().iterator(); i.hasNext(); )
{
GeneratorNode child = (GeneratorNode) i.next();
if ( child.isReferencable() || child.isReferencableChildren() )
{
value.setReferencableChildren( true );
}
value.addNodesWithReferencableChildren( child.getNodesWithReferencableChildren() );
}
return value;
}
private void writeReferenceResolvers( GeneratorNode node, JClass jClass )
{
JMethod unmarshall = new JMethod( "resolveReferences" );
unmarshall.addParameter( new JParameter( new JClass( node.getTo() ), "value" ) );
unmarshall.getModifiers().makePrivate();
JSourceCode sc = unmarshall.getSourceCode();
sc.add( "java.util.Map refs;" );
for ( Iterator i = node.getChildren().iterator(); i.hasNext(); )
{
GeneratorNode child = (GeneratorNode) i.next();
if ( child.isReferencable() )
{
ModelAssociation association = child.getAssociation();
String refFieldName = getRefFieldName( association );
String to = association.getTo();
String instanceFieldName = getInstanceFieldName( to );
sc.add( "if ( " + refFieldName + " != null )" );
sc.add( "{" );
sc.indent();
sc.add( "refs = (java.util.Map) " + refFieldName + ".get( value );" );
sc.add( "if ( refs != null )" );
sc.add( "{" );
sc.indent();
String capAssocName = capitalise( association.getName() );
if ( association.isOneMultiplicity() )
{
sc.add( "String id = (String) refs.get( \"" + association.getName() + "\" );" );
sc.add( to + " ref = (" + to + ") " + instanceFieldName + ".get( id );" );
// Don't set if it already is, since the Java plugin generates create/break that will throw an
// exception
sc.add( "if ( ref != null && !ref.equals( value.get" + capAssocName + "() ) )" );
sc.add( "{" );
sc.addIndented( "value.set" + capAssocName + "( ref );" );
sc.add( "}" );
}
else
{
sc.add( "for ( int i = 0; i < value.get" + capAssocName + "().size(); i++ )" );
sc.add( "{" );
sc.indent();
sc.add( "String id = (String) refs.get( \"" + association.getName() + ".\" + i );" );
sc.add( to + " ref = (" + to + ") " + instanceFieldName + ".get( id );" );
sc.add( "if ( ref != null )" );
sc.add( "{" );
sc.addIndented( "value.get" + capAssocName + "().set( i, ref );" );
sc.add( "}" );
sc.unindent();
sc.add( "}" );
}
sc.unindent();
sc.add( "}" );
sc.unindent();
sc.add( "}" );
}
if ( child.isReferencableChildren() )
{
ModelAssociation association = child.getAssociation();
if ( association.isOneMultiplicity() )
{
sc.add( "resolveReferences( value.get" + capitalise( association.getName() ) + "() );" );
}
else
{
sc.add( "for ( java.util.Iterator i = value.get" + capitalise( association.getName() )
+ "().iterator(); i.hasNext(); )" );
sc.add( "{" );
sc.addIndented( "resolveReferences( (" + association.getTo() + ") i.next() );" );
sc.add( "}" );
}
}
}
jClass.addMethod( unmarshall );
}
private static String getRefFieldName( ModelAssociation association )
{
return uncapitalise( association.getTo() ) + "References";
}
private static String getInstanceFieldName( String to )
{
return uncapitalise( to ) + "Instances";
}
/**
* Add code to parse fields of a model class that are XML attributes.
*
* @param modelClass the model class
* @param uncapClassName
* @param sc the source code to add to
* @throws ModelloException
*/
private void writeAttributes( ModelClass modelClass, String uncapClassName, JSourceCode sc )
throws ModelloException
{
for ( Iterator i = modelClass.getAllFields( getGeneratedVersion(), true ).iterator(); i.hasNext(); )
{
ModelField field = (ModelField) i.next();
XmlFieldMetadata xmlFieldMetadata = (XmlFieldMetadata) field.getMetadata( XmlFieldMetadata.ID );
if ( xmlFieldMetadata.isAttribute() && !xmlFieldMetadata.isTransient() )
{
writePrimitiveField( field, field.getType(), uncapClassName, "set" + capitalise( field.getName() ),
sc );
}
}
}
/**
* Generate code to process a field represented as an XML element.
*
* @param field the field to process
* @param xmlFieldMetadata its XML metadata
* @param addElse add an else
statement before generating a new if
* @param sc the method source code to add to
* @param objectName the object name in the source
* @param rootElement is the enclosing model class the root class (for model version field handling)
* @param jClass the generated class source file
* @throws ModelloException
*/
private void processField( ModelField field, XmlFieldMetadata xmlFieldMetadata, boolean addElse, JSourceCode sc,
String objectName, boolean rootElement, JClass jClass )
throws ModelloException
{
String fieldTagName = resolveTagName( field, xmlFieldMetadata );
String capFieldName = capitalise( field.getName() );
String singularName = singular( field.getName() );
String alias;
if ( StringUtils.isEmpty( field.getAlias() ) )
{
alias = "null";
}
else
{
alias = "\"" + field.getAlias() + "\"";
}
String tagComparison = ( addElse ? "else " : "" )
+ "if ( checkFieldWithDuplicate( xmlStreamReader, \"" + fieldTagName + "\", " + alias + ", parsed ) )";
if ( !( field instanceof ModelAssociation ) )
{
sc.add( tagComparison );
sc.add( "{" );
sc.indent();
//ModelField
writePrimitiveField( field, field.getType(), objectName, "set" + capFieldName, sc );
if ( rootElement && field.isModelVersionField() )
{
sc.add( "String modelVersion = " + objectName + ".get" + capFieldName + "();" );
writeModelVersionCheck( sc );
}
sc.unindent();
sc.add( "}" );
}
else
{ // model association
ModelAssociation association = (ModelAssociation) field;
String associationName = association.getName();
if ( association.isOneMultiplicity() )
{
sc.add( tagComparison );
sc.add( "{" );
sc.indent();
ModelField referenceIdentifierField = getReferenceIdentifierField( association );
if ( referenceIdentifierField != null )
{
addCodeToAddReferences( association, jClass, sc, referenceIdentifierField, objectName );
// gobble the rest of the tag
sc.add( "while ( xmlStreamReader.getEventType() != XMLStreamConstants.END_ELEMENT )" );
sc.add( "{" );
sc.addIndented( "xmlStreamReader.next();" );
sc.add( "}" );
}
else
{
sc.add( objectName + ".set" + capFieldName + "( parse" + association.getTo() + "( \"" + fieldTagName
+ "\", xmlStreamReader, strict, encoding ) );" );
}
sc.unindent();
sc.add( "}" );
}
else
{
//MANY_MULTIPLICITY
XmlAssociationMetadata xmlAssociationMetadata =
(XmlAssociationMetadata) association.getAssociationMetadata( XmlAssociationMetadata.ID );
String valuesTagName = resolveTagName( fieldTagName, xmlAssociationMetadata );
String type = association.getType();
boolean wrappedItems = xmlAssociationMetadata.isWrappedItems();
if ( ModelDefault.LIST.equals( type ) || ModelDefault.SET.equals( type ) )
{
if ( wrappedItems )
{
sc.add( tagComparison );
sc.add( "{" );
sc.indent();
sc.add( type + " " + associationName + " = " + association.getDefaultValue() + ";" );
sc.add( objectName + ".set" + capFieldName + "( " + associationName + " );" );
sc.add( "while ( xmlStreamReader.nextTag() == XMLStreamConstants.START_ELEMENT )" );
sc.add( "{" );
sc.indent();
sc.add( "if ( xmlStreamReader.getLocalName().equals( \"" + valuesTagName + "\" ) )" );
sc.add( "{" );
sc.indent();
}
else
{
sc.add( ( addElse ? "else " : "" )
+ "if ( xmlStreamReader.getLocalName().equals( \"" + valuesTagName + "\" ) )" );
sc.add( "{" );
sc.indent();
sc.add( type + " " + associationName + " = " + objectName + ".get" + capFieldName + "();" );
sc.add( "if ( " + associationName + " == null )" );
sc.add( "{" );
sc.indent();
sc.add( associationName + " = " + association.getDefaultValue() + ";" );
sc.add( objectName + ".set" + capFieldName + "( " + associationName + " );" );
sc.unindent();
sc.add( "}" );
}
if ( isClassInModel( association.getTo(), field.getModelClass().getModel() ) )
{
ModelField referenceIdentifierField = getReferenceIdentifierField( association );
if ( referenceIdentifierField != null )
{
addCodeToAddReferences( association, jClass, sc, referenceIdentifierField, objectName );
}
if ( association.getTo().equals( field.getModelClass().getName() ) )
{
// HACK: the addXXX method will cause an OOME when compiling a self-referencing class, so we
// just add it to the array. This could disrupt the links if you are using break/create
// constraints in modello.
sc.add( associationName + ".add( parse" + association.getTo() + "( \"" + valuesTagName
+ "\", xmlStreamReader, strict, encoding ) );" );
}
else
{
sc.add( objectName + ".add" + capitalise( singular( associationName ) ) + "( parse"
+ association.getTo() + "( \"" + valuesTagName
+ "\", xmlStreamReader, strict, encoding ) );" );
}
}
else
{
writePrimitiveField( association, association.getTo(), associationName, "add", sc );
}
if ( wrappedItems )
{
sc.unindent();
sc.add( "}" );
sc.add( "else" );
sc.add( "{" );
sc.addIndented( "throw new XMLStreamException( \"Unrecognised tag: '\" + "
+ "xmlStreamReader.getLocalName() + \"'\", xmlStreamReader.getLocation() );" );
sc.add( "}" );
sc.unindent();
sc.add( "}" );
sc.unindent();
sc.add( "}" );
}
else
{
sc.unindent();
sc.add( "}" );
}
}
else
{
//Map or Properties
sc.add( tagComparison );
sc.add( "{" );
sc.indent();
if ( xmlAssociationMetadata.isMapExplode() )
{
sc.add( "while ( xmlStreamReader.nextTag() == XMLStreamConstants.START_ELEMENT )" );
sc.add( "{" );
sc.indent();
sc.add( "if ( xmlStreamReader.getLocalName().equals( \"" + valuesTagName + "\" ) )" );
sc.add( "{" );
sc.indent();
sc.add( "String key = null;" );
sc.add( "String value = null;" );
sc.add( "// " + xmlAssociationMetadata.getMapStyle() + " mode." );
sc.add( "while ( xmlStreamReader.nextTag() == XMLStreamConstants.START_ELEMENT )" );
sc.add( "{" );
sc.indent();
sc.add( "if ( xmlStreamReader.getLocalName().equals( \"key\" ) )" );
sc.add( "{" );
sc.addIndented( "key = xmlStreamReader.getElementText();" );
sc.add( "}" );
sc.add( "else if ( xmlStreamReader.getLocalName().equals( \"value\" ) )" );
sc.add( "{" );
sc.addIndented( "value = xmlStreamReader.getElementText()"
+ ( xmlFieldMetadata.isTrim() ? ".trim()" : "" ) + ";" );
sc.add( "}" );
sc.add( "else" );
sc.add( "{" );
sc.addIndented( "xmlStreamReader.getText();" );
sc.add( "}" );
sc.unindent();
sc.add( "}" );
sc.add( objectName + ".add" + capitalise( singularName ) + "( key, value );" );
sc.unindent();
sc.add( "}" );
sc.add( "xmlStreamReader.next();" );
sc.unindent();
sc.add( "}" );
}
else
{
//INLINE Mode
sc.add( "while ( xmlStreamReader.nextTag() == XMLStreamConstants.START_ELEMENT )" );
sc.add( "{" );
sc.indent();
sc.add( "String key = xmlStreamReader.getLocalName();" );
sc.add( "String value = xmlStreamReader.getElementText()"
+ ( xmlFieldMetadata.isTrim() ? ".trim()" : "" ) + ";" );
sc.add( objectName + ".add" + capitalise( singularName ) + "( key, value );" );
sc.unindent();
sc.add( "}" );
}
sc.unindent();
sc.add( "}" );
}
}
}
}
private static void addCodeToAddReferences( ModelAssociation association, JClass jClass, JSourceCode sc,
ModelField referenceIdentifierField, String referredFromClass )
{
String refFieldName = getRefFieldName( association );
if ( jClass.getField( refFieldName ) == null )
{
jClass.addField( new JField( new JType( "java.util.Map" ), refFieldName ) );
}
sc.add( "String value = xmlStreamReader.getAttributeValue( null, \"" + referenceIdentifierField.getName()
+ "\" );" );
sc.add( "if ( value != null )" );
sc.add( "{" );
sc.indent();
sc.add( "// This is a reference to an element elsewhere in the model" );
sc.add( "if ( " + refFieldName + " == null )" );
sc.add( "{" );
sc.addIndented( refFieldName + " = new java.util.HashMap();" );
sc.add( "}" );
sc.add( "java.util.Map refs = (java.util.Map) " + refFieldName + ".get( " + referredFromClass + " );" );
sc.add( "if ( refs == null )" );
sc.add( "{" );
sc.indent();
sc.add( "refs = new java.util.HashMap();" );
sc.add( refFieldName + ".put( " + referredFromClass + ", refs );" );
sc.unindent();
sc.add( "}" );
if ( association.isOneMultiplicity() )
{
sc.add( "refs.put( \"" + association.getName() + "\", value );" );
}
else
{
sc.add( "refs.put( \"" + association.getName() + ".\" + " + association.getName() + ".size(), value );" );
}
sc.unindent();
sc.add( "}" );
}
private void writeModelVersionCheck( JSourceCode sc )
{
writeModelVersionHack( sc );
sc.add( "if ( !modelVersion.equals( \"" + getGeneratedVersion() + "\" ) )" );
sc.add( "{" );
sc.addIndented(
"throw new XMLStreamException( \"Document model version of '\" + modelVersion + \"' doesn't match reader "
+ "version of '" + getGeneratedVersion() + "'\", xmlStreamReader.getLocation() );" );
sc.add( "}" );
}
/**
* Write code to set a primitive field with a value got from the parser, with appropriate default value, trimming
* and required check logic.
*
* @param field the model field to set (either XML attribute or element)
* @param type the type of the value read from XML
* @param objectName the object name in source
* @param setterName the setter method name
* @param sc the source code to add to
*/
private void writePrimitiveField( ModelField field, String type, String objectName, String setterName,
JSourceCode sc )
{
XmlFieldMetadata xmlFieldMetadata = (XmlFieldMetadata) field.getMetadata( XmlFieldMetadata.ID );
String tagName = resolveTagName( field, xmlFieldMetadata);
String parserGetter;
if ( xmlFieldMetadata.isAttribute() )
{
parserGetter = "xmlStreamReader.getAttributeValue( null, \"" + tagName + "\" )";
}
else
{
parserGetter = "xmlStreamReader.getElementText()";
}
/* TODO:
if ( xmlFieldMetadata.isRequired() )
{
parserGetter = "getRequiredAttributeValue( " + parserGetter + ", \"" + tagName + "\", parser, strict, encoding )";
}
*/
if ( field.getDefaultValue() != null )
{
parserGetter = "getDefaultValue( " + parserGetter + ", \"" + field.getDefaultValue() + "\" )";
}
if ( xmlFieldMetadata.isTrim() )
{
parserGetter = "getTrimmedValue( " + parserGetter + " )";
}
if ( "boolean".equals( type ) )
{
sc.add( objectName + "." + setterName + "( getBooleanValue( " + parserGetter + ", \"" + tagName
+ "\", xmlStreamReader ) );" );
}
else if ( "char".equals( type ) )
{
sc.add( objectName + "." + setterName + "( getCharacterValue( " + parserGetter + ", \"" + tagName
+ "\", xmlStreamReader ) );" );
}
else if ( "double".equals( type ) )
{
sc.add( objectName + "." + setterName + "( getDoubleValue( " + parserGetter + ", \"" + tagName
+ "\", xmlStreamReader, strict ) );" );
}
else if ( "float".equals( type ) )
{
sc.add( objectName + "." + setterName + "( getFloatValue( " + parserGetter + ", \"" + tagName
+ "\", xmlStreamReader, strict ) );" );
}
else if ( "int".equals( type ) )
{
sc.add( objectName + "." + setterName + "( getIntegerValue( " + parserGetter + ", \"" + tagName
+ "\", xmlStreamReader, strict ) );" );
}
else if ( "long".equals( type ) )
{
sc.add( objectName + "." + setterName + "( getLongValue( " + parserGetter + ", \"" + tagName
+ "\", xmlStreamReader, strict ) );" );
}
else if ( "short".equals( type ) )
{
sc.add( objectName + "." + setterName + "( getShortValue( " + parserGetter + ", \"" + tagName
+ "\", xmlStreamReader, strict ) );" );
}
else if ( "byte".equals( type ) )
{
sc.add( objectName + "." + setterName + "( getByteValue( " + parserGetter + ", \"" + tagName
+ "\", xmlStreamReader, strict ) );" );
}
else if ( "String".equals( type ) || "Boolean".equals( type ) )
{
// TODO: other Primitive types
sc.add( objectName + "." + setterName + "( " + parserGetter + " );" );
}
else if ( "Date".equals( type ) )
{
sc.add( "String dateFormat = "
+ ( xmlFieldMetadata.getFormat() != null ? "\"" + xmlFieldMetadata.getFormat() + "\"" : "null" ) + ";" );
sc.add( objectName + "." + setterName + "( getDateValue( " + parserGetter + ", \"" + tagName
+ "\", dateFormat, xmlStreamReader ) );" );
}
else if ( "DOM".equals( type ) )
{
sc.add( objectName + "." + setterName + "( buildDom( xmlStreamReader ) );" );
}
else
{
throw new IllegalArgumentException( "Unknown type: " + type );
}
}
private void writeBuildDomMethod( JClass jClass )
{
JMethod method = new JMethod( "buildDom", new JType( "Xpp3Dom" ), null );
method.getModifiers().makePrivate();
method.addParameter( new JParameter( new JType( "XMLStreamReader" ), "xmlStreamReader" ) );
method.addException( new JClass( "XMLStreamException" ) );
JSourceCode sc = method.getSourceCode();
sc.add( "java.util.List elements = new java.util.ArrayList();" );
sc.add( "java.util.List values = new java.util.ArrayList();" );
sc.add( "int eventType = xmlStreamReader.getEventType();" );
sc.add( "while ( xmlStreamReader.hasNext() )" );
sc.add( "{" );
sc.indent();
sc.add( "if ( eventType == XMLStreamConstants.START_ELEMENT )" );
sc.add( "{" );
sc.indent();
sc.add( "String rawName = xmlStreamReader.getLocalName();" );
sc.add( "Xpp3Dom childConfiguration = new Xpp3Dom( rawName );" );
sc.add( "int depth = elements.size();" );
sc.add( "if ( depth > 0 )" );
sc.add( "{" );
sc.indent();
sc.add( "Xpp3Dom parent = (Xpp3Dom) elements.get( depth - 1 );" );
sc.add( "parent.addChild( childConfiguration );" );
sc.unindent();
sc.add( "}" );
sc.add( "elements.add( childConfiguration );" );
sc.add( "if ( xmlStreamReader.isEndElement() )" );
sc.add( "{" );
sc.addIndented( "values.add( null );" );
sc.add( "}" );
sc.add( "else" );
sc.add( "{" );
sc.addIndented( "values.add( new StringBuffer() );" );
sc.add( "}" );
sc.add( "int attributesSize = xmlStreamReader.getAttributeCount();" );
sc.add( "for ( int i = 0; i < attributesSize; i++ )" );
sc.add( "{" );
sc.indent();
sc.add( "String name = xmlStreamReader.getAttributeLocalName( i );" );
sc.add( "String value = xmlStreamReader.getAttributeValue( i );" );
sc.add( "childConfiguration.setAttribute( name, value );" );
sc.unindent();
sc.add( "}" );
sc.unindent();
sc.add( "}" );
sc.add( "else if ( eventType == XMLStreamConstants.CHARACTERS )" );
sc.add( "{" );
sc.indent();
sc.add( "int depth = values.size() - 1;" );
sc.add( "StringBuffer valueBuffer = (StringBuffer) values.get( depth );" );
sc.add( "String text = xmlStreamReader.getText();" );
sc.add( "text = text.trim();" );
sc.add( "valueBuffer.append( text );" );
sc.unindent();
sc.add( "}" );
sc.add( "else if ( eventType == XMLStreamConstants.END_ELEMENT )" );
sc.add( "{" );
sc.indent();
sc.add( "int depth = elements.size() - 1;" );
sc.add( "Xpp3Dom finishedConfiguration = (Xpp3Dom) elements.remove( depth );" );
sc.add( "// this Object could be null if it is a singleton tag" );
sc.add( "Object accumulatedValue = values.remove( depth );" );
sc.add( "if ( finishedConfiguration.getChildCount() == 0 )" );
sc.add( "{" );
sc.indent();
sc.add( "if ( accumulatedValue == null )" );
sc.add( "{" );
sc.addIndented( "finishedConfiguration.setValue( null );" );
sc.add( "}" );
sc.add( "else" );
sc.add( "{" );
sc.addIndented( "finishedConfiguration.setValue( accumulatedValue.toString() );" );
sc.add( "}" );
sc.unindent();
sc.add( "}" );
sc.add( "if ( depth == 0 )" );
sc.add( "{" );
sc.addIndented( "return finishedConfiguration;" );
sc.add( "}" );
sc.unindent();
sc.add( "}" );
sc.add( "eventType = xmlStreamReader.next();" );
sc.unindent();
sc.add( "}" );
sc.add( "throw new IllegalStateException( \"End of document found before returning to 0 depth\" );" );
jClass.addMethod( method );
}
private void writeHelpers( JClass jClass )
{
JMethod method = new JMethod( "getTrimmedValue", new JClass( "String" ), null );
method.getModifiers().makePrivate();
method.addParameter( new JParameter( new JClass( "String" ), "s" ) );
JSourceCode sc = method.getSourceCode();
sc.add( "if ( s != null )" );
sc.add( "{" );
sc.addIndented( "s = s.trim();" );
sc.add( "}" );
sc.add( "return s;" );
jClass.addMethod( method );
// --------------------------------------------------------------------
method = new JMethod( "getDefaultValue", new JClass( "String" ), null );
method.getModifiers().makePrivate();
method.addParameter( new JParameter( new JClass( "String" ), "s" ) );
method.addParameter( new JParameter( new JClass( "String" ), "v" ) );
sc = method.getSourceCode();
sc.add( "if ( s == null )" );
sc.add( "{" );
sc.addIndented( "s = v;" );
sc.add( "}" );
sc.add( "return s;" );
jClass.addMethod( method );
// --------------------------------------------------------------------
method = new JMethod( "getRequiredAttributeValue", new JClass( "String" ), null );
method.addException( new JClass( "XMLStreamException" ) );
method.getModifiers().makePrivate();
method.addParameter( new JParameter( new JClass( "String" ), "s" ) );
method.addParameter( new JParameter( new JClass( "String" ), "attribute" ) );
method.addParameter( new JParameter( new JClass( "XMLStreamReader" ), "xmlStreamReader" ) );
method.addParameter( new JParameter( JType.BOOLEAN, "strict" ) );
sc = method.getSourceCode();
sc.add( "if ( s == null )" );
sc.add( "{" );
sc.indent();
sc.add( "if ( strict )" );
sc.add( "{" );
sc.addIndented( "throw new XMLStreamException( \"Missing required value for attribute '\" + attribute + \"'\", "
+ "xmlStreamReader.getLocation() );" );
sc.add( "}" );
sc.unindent();
sc.add( "}" );
sc.add( "return s;" );
jClass.addMethod( method );
// --------------------------------------------------------------------
method = new JMethod( "getBooleanValue", JType.BOOLEAN, null );
method.addException( new JClass( "XMLStreamException" ) );
method.getModifiers().makePrivate();
method.addParameter( new JParameter( new JClass( "String" ), "s" ) );
method.addParameter( new JParameter( new JClass( "String" ), "attribute" ) );
method.addParameter( new JParameter( new JClass( "XMLStreamReader" ), "xmlStreamReader" ) );
sc = method.getSourceCode();
sc.add( "if ( s != null )" );
sc.add( "{" );
sc.addIndented( "return Boolean.valueOf( s ).booleanValue();" );
sc.add( "}" );
sc.add( "return false;" );
jClass.addMethod( method );
// --------------------------------------------------------------------
method = new JMethod( "getCharacterValue", JType.CHAR, null );
method.addException( new JClass( "XMLStreamException" ) );
method.getModifiers().makePrivate();
method.addParameter( new JParameter( new JClass( "String" ), "s" ) );
method.addParameter( new JParameter( new JClass( "String" ), "attribute" ) );
method.addParameter( new JParameter( new JClass( "XMLStreamReader" ), "xmlStreamReader" ) );
sc = method.getSourceCode();
sc.add( "if ( s != null )" );
sc.add( "{" );
sc.addIndented( "return s.charAt( 0 );" );
sc.add( "}" );
sc.add( "return 0;" );
jClass.addMethod( method );
// --------------------------------------------------------------------
method = convertNumericalType( "getIntegerValue", JType.INT, "Integer.valueOf( s ).intValue()", "an integer" );
jClass.addMethod( method );
// --------------------------------------------------------------------
method = convertNumericalType( "getShortValue", JType.SHORT, "Short.valueOf( s ).shortValue()",
"a short integer" );
jClass.addMethod( method );
// --------------------------------------------------------------------
method = convertNumericalType( "getByteValue", JType.BYTE, "Byte.valueOf( s ).byteValue()", "a byte" );
jClass.addMethod( method );
// --------------------------------------------------------------------
method = convertNumericalType( "getLongValue", JType.LONG, "Long.valueOf( s ).longValue()", "a long integer" );
jClass.addMethod( method );
// --------------------------------------------------------------------
method = convertNumericalType( "getFloatValue", JType.FLOAT, "Float.valueOf( s ).floatValue()",
"a floating point number" );
jClass.addMethod( method );
// --------------------------------------------------------------------
method = convertNumericalType( "getDoubleValue", JType.DOUBLE, "Double.valueOf( s ).doubleValue()",
"a floating point number" );
jClass.addMethod( method );
// --------------------------------------------------------------------
method = new JMethod( "getDateValue", new JClass( "java.util.Date" ), null );
method.addException( new JClass( "XMLStreamException" ) );
method.getModifiers().makePrivate();
method.addParameter( new JParameter( new JClass( "String" ), "s" ) );
method.addParameter( new JParameter( new JClass( "String" ), "attribute" ) );
method.addParameter( new JParameter( new JClass( "String" ), "dateFormat" ) );
method.addParameter( new JParameter( new JClass( "XMLStreamReader" ), "xmlStreamReader" ) );
method.addException( new JClass( "XMLStreamException" ) );
writeDateParsingHelper( method.getSourceCode(), "new XMLStreamException( e.getMessage() )" );
jClass.addMethod( method );
// --------------------------------------------------------------------
method = new JMethod( "checkFieldWithDuplicate", JType.BOOLEAN, null );
method.getModifiers().makePrivate();
method.addParameter( new JParameter( new JClass( "XMLStreamReader" ), "xmlStreamReader" ) );
method.addParameter( new JParameter( new JClass( "String" ), "tagName" ) );
method.addParameter( new JParameter( new JClass( "String" ), "alias" ) );
method.addParameter( new JParameter( new JClass( "java.util.Set" ), "parsed" ) );
method.addException( new JClass( "XMLStreamException" ) );
sc = method.getSourceCode();
sc.add( "if ( !( xmlStreamReader.getLocalName().equals( tagName ) ||"
+ " xmlStreamReader.getLocalName().equals( alias ) ) )" );
sc.add( "{" );
sc.addIndented( "return false;" );
sc.add( "}" );
sc.add( "if ( parsed.contains( tagName ) )" );
sc.add( "{" );
sc.addIndented(
"throw new XMLStreamException( \"Duplicated tag: '\" + tagName + \"'\", xmlStreamReader.getLocation() );" );
sc.add( "}" );
sc.add( "parsed.add( tagName );" );
sc.add( "return true;" );
jClass.addMethod( method );
}
private JMethod convertNumericalType( String methodName, JType returnType, String expression, String typeDesc )
{
JMethod method = new JMethod( methodName, returnType, null );
method.addException( new JClass( "XMLStreamException" ) );
method.getModifiers().makePrivate();
method.addParameter( new JParameter( new JClass( "String" ), "s" ) );
method.addParameter( new JParameter( new JClass( "String" ), "attribute" ) );
method.addParameter( new JParameter( new JClass( "XMLStreamReader" ), "xmlStreamReader" ) );
method.addParameter( new JParameter( JType.BOOLEAN, "strict" ) );
JSourceCode sc = method.getSourceCode();
sc.add( "if ( s != null )" );
sc.add( "{" );
sc.indent();
sc.add( "try" );
sc.add( "{" );
sc.addIndented( "return " + expression + ";" );
sc.add( "}" );
sc.add( "catch ( NumberFormatException e )" );
sc.add( "{" );
sc.indent();
sc.add( "if ( strict )" );
sc.add( "{" );
sc.addIndented( "throw new XMLStreamException( \"Unable to parse element '\" + attribute + \"', must be "
+ typeDesc + " but was '\" + s + \"'\", xmlStreamReader.getLocation() );" );
sc.add( "}" );
sc.unindent();
sc.add( "}" );
sc.unindent();
sc.add( "}" );
sc.add( "return 0;" );
return method;
}
}
././@LongLink 0000000 0000000 0000000 00000000170 00000000000 011563 L ustar root root modello-1.1/modello-plugins/modello-plugin-stax/src/main/java/org/codehaus/modello/plugin/stax/StaxWriterGenerator.java modello-1.1/modello-plugins/modello-plugin-stax/src/main/java/org/codehaus/modello/plugin/stax/StaxW0000644 0001750 0001750 00000055301 11243356043 032734 0 ustar mkoch mkoch package org.codehaus.modello.plugin.stax;
/*
* Copyright (c) 2004, Codehaus.org
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is furnished to do
* so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
import org.codehaus.modello.ModelloException;
import org.codehaus.modello.model.Model;
import org.codehaus.modello.model.ModelAssociation;
import org.codehaus.modello.model.ModelClass;
import org.codehaus.modello.model.ModelDefault;
import org.codehaus.modello.model.ModelField;
import org.codehaus.modello.plugin.java.javasource.JClass;
import org.codehaus.modello.plugin.java.javasource.JConstructor;
import org.codehaus.modello.plugin.java.javasource.JField;
import org.codehaus.modello.plugin.java.javasource.JMethod;
import org.codehaus.modello.plugin.java.javasource.JParameter;
import org.codehaus.modello.plugin.java.javasource.JSourceCode;
import org.codehaus.modello.plugin.java.javasource.JSourceWriter;
import org.codehaus.modello.plugin.java.javasource.JType;
import org.codehaus.modello.plugin.java.metadata.JavaClassMetadata;
import org.codehaus.modello.plugin.java.metadata.JavaFieldMetadata;
import org.codehaus.modello.plugin.model.ModelClassMetadata;
import org.codehaus.modello.plugins.xml.metadata.XmlAssociationMetadata;
import org.codehaus.modello.plugins.xml.metadata.XmlFieldMetadata;
import org.codehaus.modello.plugins.xml.metadata.XmlModelMetadata;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
/**
* @author Jason van Zyl
* @author Emmanuel Venisse
* @version $Id: StaxWriterGenerator.java 1311 2009-08-20 23:28:35Z hboutemy $
*/
public class StaxWriterGenerator
extends AbstractStaxGenerator
{
public void generate( Model model, Properties parameters )
throws ModelloException
{
initialize( model, parameters );
try
{
generateStaxWriter();
}
catch ( IOException ex )
{
throw new ModelloException( "Exception while generating StAX Writer.", ex );
}
}
private void generateStaxWriter()
throws ModelloException, IOException
{
Model objectModel = getModel();
String packageName = objectModel.getDefaultPackageName( isPackageWithVersion(), getGeneratedVersion() )
+ ".io.stax";
String marshallerName = getFileName( "StaxWriter" );
JSourceWriter sourceWriter = newJSourceWriter( packageName, marshallerName );
JClass jClass = new JClass( packageName + '.' + marshallerName );
initHeader( jClass );
suppressAllWarnings( objectModel, jClass );
jClass.addImport( "java.io.InputStream" );
jClass.addImport( "java.io.IOException" );
jClass.addImport( "java.io.Writer" );
jClass.addImport( "java.io.StringWriter" );
jClass.addImport( "java.text.DateFormat" );
jClass.addImport( "java.util.Iterator" );
jClass.addImport( "java.util.Locale" );
jClass.addImport( "java.util.jar.Manifest" );
jClass.addImport( "javax.xml.stream.*" );
jClass.addImport( "javanet.staxutils.IndentingXMLStreamWriter" );
jClass.addImport( "org.codehaus.plexus.util.xml.Xpp3Dom" );
addModelImports( jClass, null );
jClass.addField( new JField( JType.INT, "curId" ) );
jClass.addField( new JField( new JType( "java.util.Map" ), "idMap" ) );
JConstructor constructor = new JConstructor( jClass );
constructor.getSourceCode().add( "idMap = new java.util.HashMap();" );
jClass.addConstructor( constructor );
String root = objectModel.getRoot( getGeneratedVersion() );
ModelClass rootClass = objectModel.getClass( root, getGeneratedVersion() );
String rootElement = resolveTagName( rootClass );
// Write the parse method which will do the unmarshalling.
JMethod marshall = new JMethod( "write" );
String rootElementParameterName = uncapitalise( root );
marshall.addParameter( new JParameter( new JClass( "Writer" ), "writer" ) );
marshall.addParameter( new JParameter( new JClass( root ), rootElementParameterName ) );
marshall.addException( new JClass( "java.io.IOException" ) );
marshall.addException( new JClass( "XMLStreamException" ) );
JSourceCode sc = marshall.getSourceCode();
sc.add( "XMLOutputFactory factory = XMLOutputFactory.newInstance();" );
// currently, only woodstox supports Windows line endings. It works with Java 6/RI and stax <= 1.1.1 as well
// but we have no way to detect them
sc.add( "boolean supportWindowsLineEndings = false;" );
sc.add( "if ( factory.isPropertySupported( \"com.ctc.wstx.outputEscapeCr\" ) )" );
sc.add( "{" );
sc.indent();
sc.add( "factory.setProperty( \"com.ctc.wstx.outputEscapeCr\", Boolean.FALSE );" );
sc.add( "supportWindowsLineEndings = true;" );
sc.unindent();
sc.add( "}" );
sc.add( "if ( factory.isPropertySupported( \"org.codehaus.stax2.automaticEmptyElements\" ) )" );
sc.add( "{" );
sc.addIndented( "factory.setProperty( \"org.codehaus.stax2.automaticEmptyElements\", Boolean.FALSE );" );
sc.add( "}" );
sc.add(
"IndentingXMLStreamWriter serializer = new IndentingXMLStreamWriter( factory.createXMLStreamWriter( writer ) );" );
sc.add( "if ( supportWindowsLineEndings )" );
sc.add( "{" );
sc.addIndented( "serializer.setNewLine( serializer.getLineSeparator() );" );
sc.add( "}" );
sc.add( "serializer.writeStartDocument( " + rootElementParameterName + ".getModelEncoding(), \"1.0\" );" );
sc.add( "write" + root + "( " + rootElementParameterName + ", \"" + rootElement + "\", serializer );" );
sc.add( "serializer.writeEndDocument();" );
jClass.addMethod( marshall );
createWriteDomMethod( jClass );
writeAllClasses( objectModel, jClass );
jClass.print( sourceWriter );
sourceWriter.close();
}
private void writeAllClasses( Model objectModel, JClass jClass )
throws ModelloException
{
for ( Iterator i = objectModel.getClasses( getGeneratedVersion() ).iterator(); i.hasNext(); )
{
ModelClass clazz = (ModelClass) i.next();
JavaClassMetadata javaClassMetadata = (JavaClassMetadata) clazz.getMetadata( JavaClassMetadata.ID );
if ( !javaClassMetadata.isEnabled() )
{
// Skip import of those classes that are not enabled for the java plugin.
continue;
}
writeClass( clazz, jClass );
}
}
private void writeClass( ModelClass modelClass, JClass jClass )
throws ModelloException
{
String className = modelClass.getName();
String uncapClassName = uncapitalise( className );
JMethod marshall = new JMethod( "write" + className );
marshall.getModifiers().makePrivate();
marshall.addParameter( new JParameter( new JClass( className ), uncapClassName ) );
marshall.addParameter( new JParameter( new JClass( "String" ), "tagName" ) );
marshall.addParameter( new JParameter( new JClass( "XMLStreamWriter" ), "serializer" ) );
marshall.addException( new JClass( "java.io.IOException" ) );
marshall.addException( new JClass( "XMLStreamException" ) );
JSourceCode sc = marshall.getSourceCode();
sc.add( "if ( " + uncapClassName + " != null )" );
sc.add( "{" );
sc.indent();
ModelClassMetadata classMetadata = (ModelClassMetadata) modelClass.getMetadata( ModelClassMetadata.ID );
String namespace = null;
XmlModelMetadata xmlModelMetadata = (XmlModelMetadata) modelClass.getModel().getMetadata( XmlModelMetadata.ID );
// add namespace information for root element only
if ( classMetadata.isRootElement() && ( xmlModelMetadata.getNamespace() != null ) )
{
namespace = xmlModelMetadata.getNamespace( getGeneratedVersion() );
sc.add( "serializer.setDefaultNamespace( \"" + namespace + "\" );" );
}
sc.add( "serializer.writeStartElement( tagName );" );
if ( namespace != null )
{
sc.add( "serializer.writeDefaultNamespace( \"" + namespace + "\" );" );
if ( xmlModelMetadata.getSchemaLocation() != null )
{
String url = xmlModelMetadata.getSchemaLocation( getGeneratedVersion() );
sc.add( "serializer.setPrefix( \"xsi\", \"http://www.w3.org/2001/XMLSchema-instance\" );" );
sc.add( "serializer.writeNamespace( \"xsi\", \"http://www.w3.org/2001/XMLSchema-instance\" );" );
sc.add(
"serializer.writeAttribute( \"http://www.w3.org/2001/XMLSchema-instance\", \"schemaLocation\", \"" +
namespace + " " + url + "\" );" );
}
}
if ( isAssociationPartToClass( modelClass ) )
{
if ( modelClass.getIdentifierFields( getGeneratedVersion() ).size() != 1 )
{
writeIdMapCheck( sc, uncapClassName, "modello.id" );
}
}
ModelField contentField = null;
String contentValue = null;
List modelFields = modelClass.getAllFields( getGeneratedVersion(), true );
modelFields = getNonTransientFields( modelFields );
// XML attributes
for ( Iterator i = modelFields.iterator(); i.hasNext(); )
{
ModelField field = (ModelField) i.next();
XmlFieldMetadata xmlFieldMetadata = (XmlFieldMetadata) field.getMetadata( XmlFieldMetadata.ID );
String fieldTagName = resolveTagName( field, xmlFieldMetadata );
String type = field.getType();
String value = getFieldValue( uncapClassName, field );
if ( xmlFieldMetadata.isContent() )
{
contentField = field;
contentValue = value;
continue;
}
if ( xmlFieldMetadata.isAttribute() )
{
sc.add( getValueChecker( type, value, field ) );
sc.add( "{" );
sc.addIndented( "serializer.writeAttribute( \"" + fieldTagName + "\", " +
getValue( field.getType(), value, xmlFieldMetadata ) + " );" );
sc.add( "}" );
}
}
if ( contentField != null )
{
XmlFieldMetadata xmlFieldMetadata = (XmlFieldMetadata) contentField.getMetadata( XmlFieldMetadata.ID );
sc.add( "serializer.writeCharacters( " + getValue( contentField.getType(), contentValue, xmlFieldMetadata ) + " );" );
}
// XML tags
for ( Iterator fieldIterator = modelFields.iterator(); fieldIterator.hasNext(); )
{
ModelField field = (ModelField) fieldIterator.next();
XmlFieldMetadata xmlFieldMetadata = (XmlFieldMetadata) field.getMetadata( XmlFieldMetadata.ID );
if ( xmlFieldMetadata.isContent() )
{
// skip field with type Content
continue;
}
String fieldTagName = resolveTagName( field, xmlFieldMetadata );
String type = field.getType();
String value = getFieldValue( uncapClassName, field );
if ( xmlFieldMetadata.isAttribute() )
{
continue;
}
if ( field instanceof ModelAssociation )
{
ModelAssociation association = (ModelAssociation) field;
String associationName = association.getName();
ModelField referenceIdentifierField = getReferenceIdentifierField( association );
if ( association.isOneMultiplicity() )
{
sc.add( getValueChecker( type, value, association ) );
sc.add( "{" );
sc.indent();
if ( referenceIdentifierField != null )
{
// if xml.reference, then store as a reference instead
sc.add( "serializer.writeStartElement( \"" + fieldTagName + "\" );" );
writeElementAttribute( sc, referenceIdentifierField, value );
sc.add( "serializer.writeEndElement();" );
}
else
{
sc.add( "write" + association.getTo() + "( (" + association.getTo() + ") " + value + ", \"" +
fieldTagName + "\", serializer );" );
}
sc.unindent();
sc.add( "}" );
}
else
{
//MANY_MULTIPLICITY
XmlAssociationMetadata xmlAssociationMetadata =
(XmlAssociationMetadata) association.getAssociationMetadata( XmlAssociationMetadata.ID );
String valuesTagName = resolveTagName( fieldTagName, xmlAssociationMetadata );
type = association.getType();
String toType = association.getTo();
boolean wrappedItems = xmlAssociationMetadata.isWrappedItems();
if ( ModelDefault.LIST.equals( type ) || ModelDefault.SET.equals( type ) )
{
sc.add( getValueChecker( type, value, association ) );
sc.add( "{" );
sc.indent();
if ( wrappedItems )
{
sc.add( "serializer.writeStartElement( " + "\"" + fieldTagName + "\" );" );
}
sc.add( "for ( Iterator iter = " + value + ".iterator(); iter.hasNext(); )" );
sc.add( "{" );
sc.indent();
if ( isClassInModel( association.getTo(), modelClass.getModel() ) )
{
sc.add( toType + " o = (" + toType + ") iter.next();" );
if ( referenceIdentifierField != null )
{
sc.add( "serializer.writeStartElement( \"" + valuesTagName + "\" );" );
writeElementAttribute( sc, referenceIdentifierField, "o" );
sc.add( "serializer.writeEndElement();" );
}
else
{
sc.add( "write" + toType + "( o, \"" + valuesTagName + "\", serializer );" );
}
}
else
{
sc.add( toType + " " + singular( uncapitalise( field.getName() ) ) + " = (" + toType +
") iter.next();" );
sc.add( "serializer.writeStartElement( " + "\"" + valuesTagName + "\" );" );
sc.add(
"serializer.writeCharacters( " + singular( uncapitalise( field.getName() ) ) + " );" );
sc.add( "serializer.writeEndElement();" );
}
sc.unindent();
sc.add( "}" );
if ( wrappedItems )
{
sc.add( "serializer.writeEndElement();" );
}
sc.unindent();
sc.add( "}" );
}
else
{
//Map or Properties
sc.add( getValueChecker( type, value, field ) );
sc.add( "{" );
sc.indent();
if ( wrappedItems )
{
sc.add( "serializer.writeStartElement( " + "\"" + fieldTagName + "\" );" );
}
sc.add( "for ( Iterator iter = " + value + ".keySet().iterator(); iter.hasNext(); )" );
sc.add( "{" );
sc.indent();
sc.add( "String key = (String) iter.next();" );
sc.add( "String value = (String) " + value + ".get( key );" );
if ( xmlAssociationMetadata.isMapExplode() )
{
sc.add( "serializer.writeStartElement( \"" + singular( associationName ) + "\" );" );
sc.add( "serializer.writeStartElement( \"key\" );" );
sc.add( "serializer.writeCharacters( key );" );
sc.add( "serializer.writeEndElement();" );
sc.add( "serializer.writeStartElement( \"value\" );" );
sc.add( "serializer.writeCharacters( value );" );
sc.add( "serializer.writeEndElement();" );
sc.add( "serializer.writeEndElement();" );
}
else
{
sc.add( "serializer.writeStartElement( \"\" + key + \"\" );" );
sc.add( "serializer.writeCharacters( value );" );
sc.add( "serializer.writeEndElement();" );
}
sc.unindent();
sc.add( "}" );
if ( wrappedItems )
{
sc.add( "serializer.writeEndElement();" );
}
sc.unindent();
sc.add( "}" );
}
}
}
else
{
sc.add( getValueChecker( type, value, field ) );
sc.add( "{" );
sc.indent();
if ( "DOM".equals( field.getType() ) )
{
sc.add( "writeDom( (Xpp3Dom) " + value + ", serializer );" );
}
else
{
sc.add( "serializer.writeStartElement( " + "\"" + fieldTagName + "\" );" );
sc.add(
"serializer.writeCharacters( " + getValue( field.getType(), value, xmlFieldMetadata ) + " );" );
sc.add( "serializer.writeEndElement();" );
}
sc.unindent();
sc.add( "}" );
}
}
sc.add( "serializer.writeEndElement();" );
sc.unindent();
sc.add( "}" );
jClass.addMethod( marshall );
}
private void writeElementAttribute( JSourceCode sc, ModelField referenceIdentifierField, String value )
{
if ( referenceIdentifierField instanceof DummyIdModelField )
{
writeIdMapCheck( sc, value, referenceIdentifierField.getName() );
}
else
{
String v = getValue( referenceIdentifierField.getType(), getFieldValue( value, referenceIdentifierField ),
(XmlFieldMetadata) referenceIdentifierField.getMetadata( XmlFieldMetadata.ID ) );
sc.add( "serializer.writeAttribute( \"" + referenceIdentifierField.getName() + "\", " + v + " );" );
}
}
private static void writeIdMapCheck( JSourceCode sc, String value, String attributeName )
{
sc.add( "if ( !idMap.containsKey( " + value + " ) )" );
sc.add( "{" );
sc.indent();
sc.add( "++curId;" );
sc.add( "String id = String.valueOf( curId );" );
sc.add( "idMap.put( " + value + ", id );" );
sc.add( "serializer.writeAttribute( \"" + attributeName + "\", id );" );
sc.unindent();
sc.add( "}" );
sc.add( "else" );
sc.add( "{" );
sc.addIndented( "serializer.writeAttribute( \"" + attributeName + "\", (String) idMap.get( " + value + " ) );" );
sc.add( "}" );
}
private String getFieldValue( String uncapClassName, ModelField field )
{
JavaFieldMetadata javaFieldMetadata = (JavaFieldMetadata) field.getMetadata( JavaFieldMetadata.ID );
return uncapClassName + "." + getPrefix( javaFieldMetadata ) + capitalise( field.getName() ) + "()";
}
private void createWriteDomMethod( JClass jClass )
{
JMethod method = new JMethod( "writeDom" );
method.getModifiers().makePrivate();
method.addParameter( new JParameter( new JType( "Xpp3Dom" ), "dom" ) );
method.addParameter( new JParameter( new JType( "XMLStreamWriter" ), "serializer" ) );
method.addException( new JClass( "XMLStreamException" ) );
JSourceCode sc = method.getSourceCode();
sc.add( "serializer.writeStartElement( dom.getName() );" );
sc.add( "String[] attributeNames = dom.getAttributeNames();" );
sc.add( "for ( int i = 0; i < attributeNames.length; i++ )" );
sc.add( "{" );
sc.indent();
sc.add( "String attributeName = attributeNames[i];" );
sc.add( "serializer.writeAttribute( attributeName, dom.getAttribute( attributeName ) );" );
sc.unindent();
sc.add( "}" );
sc.add( "Xpp3Dom[] children = dom.getChildren();" );
sc.add( "for ( int i = 0; i < children.length; i++ )" );
sc.add( "{" );
sc.addIndented( "writeDom( children[i], serializer );" );
sc.add( "}" );
sc.add( "String value = dom.getValue();" );
sc.add( "if ( value != null )" );
sc.add( "{" );
sc.addIndented( "serializer.writeCharacters( value );" );
sc.add( "}" );
sc.add( "serializer.writeEndElement();" );
jClass.addMethod( method );
}
}
././@LongLink 0000000 0000000 0000000 00000000162 00000000000 011564 L ustar root root modello-1.1/modello-plugins/modello-plugin-stax/src/main/java/org/codehaus/modello/plugin/stax/GeneratorNode.java modello-1.1/modello-plugins/modello-plugin-stax/src/main/java/org/codehaus/modello/plugin/stax/Gener0000644 0001750 0001750 00000007062 11127507731 032732 0 ustar mkoch mkoch package org.codehaus.modello.plugin.stax;
import org.codehaus.modello.model.ModelAssociation;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
/*
* Copyright (c) 2006, Codehaus.org
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is furnished to do
* so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
class GeneratorNode
{
private final String to;
private boolean referencableChildren;
private List children = new LinkedList();
private ModelAssociation association;
private boolean referencable;
private Map nodesWithReferencableChildren = new HashMap();
private List chain;
GeneratorNode( String to, GeneratorNode parent )
{
this( to, parent, null );
}
GeneratorNode( ModelAssociation association, GeneratorNode parent )
{
this( association.getTo(), parent, association );
}
private GeneratorNode( String to, GeneratorNode parent, ModelAssociation association )
{
this.to = to;
this.association = association;
this.chain = parent != null ? new ArrayList( parent.getChain() ) : new ArrayList();
this.chain.add( to );
}
public boolean isReferencableChildren()
{
return referencableChildren;
}
public void setReferencableChildren( boolean referencableChildren )
{
this.referencableChildren = referencableChildren;
}
public void addChild( GeneratorNode child )
{
children.add( child );
if ( child.referencableChildren )
{
nodesWithReferencableChildren.put( child.to, child );
}
}
public List getChildren()
{
return children;
}
public String toString()
{
return "to = " + to + "; referencableChildren = " + referencableChildren + "; children = " + children;
}
public String getTo()
{
return to;
}
public ModelAssociation getAssociation()
{
return association;
}
public void setAssociation( ModelAssociation association )
{
this.association = association;
}
public void setReferencable( boolean referencable )
{
this.referencable = referencable;
}
public boolean isReferencable()
{
return referencable;
}
public Map getNodesWithReferencableChildren()
{
return nodesWithReferencableChildren;
}
public void addNodesWithReferencableChildren( Map allChildNodes )
{
this.nodesWithReferencableChildren.putAll( allChildNodes );
}
public List getChain()
{
return chain;
}
}
././@LongLink 0000000 0000000 0000000 00000000172 00000000000 011565 L ustar root root modello-1.1/modello-plugins/modello-plugin-stax/src/main/java/org/codehaus/modello/plugin/stax/AbstractStaxGenerator.java modello-1.1/modello-plugins/modello-plugin-stax/src/main/java/org/codehaus/modello/plugin/stax/Abstr0000644 0001750 0001750 00000011124 11133474166 032741 0 ustar mkoch mkoch package org.codehaus.modello.plugin.stax;
/*
* Copyright (c) 2004, Jason van Zyl
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is furnished to do
* so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
import org.codehaus.modello.ModelloException;
import org.codehaus.modello.model.Model;
import org.codehaus.modello.model.ModelAssociation;
import org.codehaus.modello.model.ModelClass;
import org.codehaus.modello.model.ModelField;
import org.codehaus.modello.plugins.xml.AbstractXmlJavaGenerator;
import org.codehaus.modello.plugins.xml.metadata.XmlAssociationMetadata;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import java.util.Set;
/**
* @author Trygve Laugstøl
* @version $Id: AbstractStaxGenerator.java 1136 2009-01-14 23:42:46Z hboutemy $
*/
public abstract class AbstractStaxGenerator
extends AbstractXmlJavaGenerator
{
private Set/*Modello JDOM Plugin generates XML writers based on JDOM API. It attempts to preserve formatting of not changed elements and even with the changed ones it does some tricks to keep the formatting in line with the rest.
jdom-writer
generator creates
my.model.package.io.jdom.ModelNameJDOMWriter
class with following
public methods:
public void write( RootClass root, Document document, OutputStream stream )
throws IOException
public void write( RootClass root, Document document, OutputStreamWriter writer )
throws IOException
public void write( RootClass root, Document document, Writer writer, Format jdomFormat )
throws IOException
public void setVersion(String version)
{
this.currentVersion = version;
}
public String getVersion()
{
return currentVersion;
}
private String packageName;
public void setPackage(String packageName)
{
this.packageName = packageName;
}
public String getPackage()
{
return packageName;
}
public String getId()
{
StringBuffer id = new StringBuffer();
id.append( getGroupId() );
id.append( ":" );
id.append( getArtifactId() );
id.append( ":" );
id.append( getType() );
id.append( ":" );
id.append( getVersion() );
return id.toString();
}
plugin
.
]]>war.bundle
property, and if found will include the dependency
in
WEB-INF/lib
. For example syntax, check the war plugin docs.
]]>
public String toString()
{
return groupId + "/" + type + "s:" + artifactId + "-" + version;
}
public String getId()
{
return groupId + ":" + artifactId + ":" + type + ":" + version;
}
element is explicity used in the POM.
if ( getJar() != null)
{
return getJar();
}
return getArtifactId() + "-" + getVersion() + "." + getExtension();
}
public String getExtension()
{
if ("ejb".equals(getType()) || "plugin".equals(getType()) || "aspect".equals(getType())) return "jar";
return getType();
}
public boolean isAddedToClasspath()
{
return ("jar".equals(getType()) || "ejb".equals(getType()));
}
public boolean isPlugin()
{
return ("plugin".equals(getType()));
}
public String getProperty( String property )
{
return getProperties().getProperty( property );
}
public boolean equals( Object o )
{
if ( this == o )
{
return true;
}
if ( !( o instanceof Dependency ) )
{
return false;
}
Dependency d = (Dependency) o;
return getId().equals( d.getId() );
}
public int hashCode()
{
return getId().hashCode();
}
]]>
plugin
.
]]>http://my.corp/logo.png
). This value is used
when generating the project documentation.
]]>
public java.util.List getDefaultExcludes()
{
java.util.List defaultExcludes = new java.util.ArrayList();
defaultExcludes.add( "**/*~" );
defaultExcludes.add( "**/#*#" );
defaultExcludes.add( "**/.#*" );
defaultExcludes.add( "**/%*%" );
defaultExcludes.add( "**/._*" );
// CVS
defaultExcludes.add( "**/CVS" );
defaultExcludes.add( "**/CVS/**" );
defaultExcludes.add( "**/.cvsignore" );
// SCCS
defaultExcludes.add( "**/SCCS" );
defaultExcludes.add( "**/SCCS/**" );
// Visual SourceSafe
defaultExcludes.add( "**/vssver.scc" );
// Subversion
defaultExcludes.add( "**/.svn" );
defaultExcludes.add( "**/.svn/**" );
// Mac
defaultExcludes.add( "**/.DS_Store" );
return defaultExcludes;
}
org/apache/maven/messages
]]>1.1-alpha1
,
1.2-beta
,
1.3.2
etc.
]]>maven:dist
builds.
]]>
public boolean equals( Object obj )
{
Repository other = ( Repository ) obj;
boolean retValue = false;
if ( id != null )
{
retValue = id.equals( other.id );
}
return retValue;
}
Modello Model Version Converter Plugin generates code to transform a model between two versions.
The source model version to convert from is in modello.version
parameter: noted
A.B.C
.
The target model version is the greatest of modello.all.versions
parameter: noted
X.Y.Z
.
converters
generator creates
my.model.package.vA_B_C.converter.VersionConverter
interface and a
BasicVersionConverter
class implementing the interface to convert a class model from version
A.B.C
to X.Y.Z
. If versions are different, model classes are supposed to be available
in their corresponding java packages with version. If versions are equals, model classes are supposed to be
available in the java package both with and without version, the package with version being the source model
and the package without version being the target.
For every class in the source model, a method is generated in the interface and an automatic implementation generated in the class with following signature:
public my.model.package[.vX_Y_Z].ModelClass convertModelClass(
my.model.package.vA_B_C.ModelClass )
In addition, if source and target versions are equals, a
my.model.package.converter.ConverterTool
is generated to automate reading a file,
detect its model version (using StAX reader delegate generated code), and convert it to the target model version
in the java package without version using generated BasicVersionConverter
class:
public my.model.package.RootClass convertFromFile( File f )
throws IOException, XMLStreamException
public void setVersion(String version)
{
this.currentVersion = version;
}
public String getVersion()
{
return currentVersion;
}
private String packageName;
public void setPackage(String packageName)
{
this.packageName = packageName;
}
public String getPackage()
{
return packageName;
}
public String getId()
{
StringBuffer id = new StringBuffer();
id.append( getGroupId() );
id.append( ":" );
id.append( getArtifactId() );
id.append( ":" );
id.append( getType() );
id.append( ":" );
id.append( getVersion() );
return id.toString();
}
plugin
.
]]>war.bundle
property, and if found will include the dependency
in
WEB-INF/lib
. For example syntax, check the war plugin docs.
]]>
public String toString()
{
return groupId + "/" + type + "s:" + artifactId + "-" + version;
}
public String getId()
{
return groupId + ":" + artifactId + ":" + type + ":" + version;
}
element is explicity used in the POM.
if ( getJar() != null)
{
return getJar();
}
return getArtifactId() + "-" + getVersion() + "." + getExtension();
}
public String getExtension()
{
if ("ejb".equals(getType()) || "plugin".equals(getType()) || "aspect".equals(getType())) return "jar";
return getType();
}
public boolean isAddedToClasspath()
{
return ("jar".equals(getType()) || "ejb".equals(getType()));
}
public boolean isPlugin()
{
return ("plugin".equals(getType()));
}
public String getProperty( String property )
{
return getProperties().getProperty( property );
}
public boolean equals( Object o )
{
if ( this == o )
{
return true;
}
if ( !( o instanceof Dependency ) )
{
return false;
}
Dependency d = (Dependency) o;
return getId().equals( d.getId() );
}
public int hashCode()
{
return getId().hashCode();
}
]]>
plugin
.
]]>http://my.corp/logo.png
). This value is used
when generating the project documentation.
]]>
public java.util.List getDefaultExcludes()
{
java.util.List defaultExcludes = new java.util.ArrayList();
defaultExcludes.add( "**/*~" );
defaultExcludes.add( "**/#*#" );
defaultExcludes.add( "**/.#*" );
defaultExcludes.add( "**/%*%" );
defaultExcludes.add( "**/._*" );
// CVS
defaultExcludes.add( "**/CVS" );
defaultExcludes.add( "**/CVS/**" );
defaultExcludes.add( "**/.cvsignore" );
// SCCS
defaultExcludes.add( "**/SCCS" );
defaultExcludes.add( "**/SCCS/**" );
// Visual SourceSafe
defaultExcludes.add( "**/vssver.scc" );
// Subversion
defaultExcludes.add( "**/.svn" );
defaultExcludes.add( "**/.svn/**" );
// Mac
defaultExcludes.add( "**/.DS_Store" );
return defaultExcludes;
}
org/apache/maven/messages
]]>1.1-alpha1
,
1.2-beta
,
1.3.2
etc.
]]>maven:dist
builds.
]]>
public boolean equals( Object obj )
{
Repository other = ( Repository ) obj;
boolean retValue = false;
if ( id != null )
{
retValue = id.equals( other.id );
}
return retValue;
}
* This method is implemented by subclasses and * should only accept the proper fields for the * subclass otherwise an IllegalArgumentException * will be thrown. For example a JInterface will * only accept static fields. *
* @param jField, the JField to add * @exception java.lang.IllegalArgumentException when the given * JField has a name of an existing JField */ public abstract void addField( JField jField ) throws IllegalArgumentException; /** * Adds the given JMember to this JStructure. *
* This method is implemented by subclasses and * should only accept the proper types for the * subclass otherwise an IllegalArgumentException * will be thrown. *
* @param jMember the JMember to add to this JStructure.
* @throws java.lang.IllegalArgumentException when the given
* JMember has the same name of an existing JField
* or JMethod respectively.
*/
public abstract void addMember( JMember jMember )
throws IllegalArgumentException;
/**
* Adds the given import to this JStructure
*
* @param the className of the class to import.
*/
public void addImport( String className )
{
if ( className == null ) return;
if ( className.length() == 0 ) return;
//-- getPackageName
String pkgName = getPackageFromClassName( className );
if ( pkgName != null )
{
if ( pkgName.equals( this.packageName ) ) return;
//-- XXX: Fix needed for this...
//-- This may cause issues if the current package
//-- defines any classes that have the same name
//-- name as the java.lang package.
if ( pkgName.equals( "java.lang" ) ) return;
//-- for readabilty keep import list sorted, and make sure
//-- we do not include more than one of the same import
for ( int i = 0; i < imports.size(); i++ )
{
String imp = (String) imports.elementAt( i );
if ( imp.equals( className ) ) return;
if ( imp.compareTo( className ) > 0 )
{
imports.insertElementAt( className, i );
return;
}
}
imports.addElement( className );
}
} //-- addImport
/**
* Adds the given interface to the list of interfaces this
* JStructure inherits method declarations from, and either
* implements (JClass) or extends (JInterface).
*
* @param interfaceName the name of the interface to "inherit"
* method declarations from.
*/
public void addInterface( String interfaceName )
{
if ( !interfaces.contains( interfaceName ) )
interfaces.addElement( interfaceName );
} //-- addInterface
/**
* Adds the given interface to the list of interfaces this
* JStructure inherits method declarations from, and either
* implements (JClass) or extends (JInterface).
*
* @param jInterface the JInterface to inherit from.
*/
public void addInterface( JInterface jInterface )
{
if ( jInterface == null ) return;
String interfaceName = jInterface.getName();
if ( !interfaces.contains( interfaceName ) )
{
interfaces.addElement( interfaceName );
}
} //-- addInterface
/**
* Adds the given JMethodSignature to this JClass
*
* @param jMethodSig the JMethodSignature to add.
* @throws java.lang.IllegalArgumentException when the given
* JMethodSignature conflicts with an existing
* method signature.
*/
/*
public void addMethod(JMethodSignature jMethodSig)
throws IllegalArgumentException
{
if (jMethodSig == null) {
String err = "The JMethodSignature cannot be null.";
throw new IllegalArgumentException(err);
}
//-- XXXX: check method name and signatures *add later*
//-- keep method list sorted for esthetics when printing
//-- START SORT :-)
boolean added = false;
short modifierVal = 0;
JModifiers modifiers = jMethodSig.getModifiers();
for (int i = 0; i < methods.size(); i++) {
JMethodSignature tmp = (JMethodSignature) methods.elementAt(i);
//-- first compare modifiers
if (tmp.getModifiers().isProtected()) {
if (!modifiers.isProtected()) {
methods.insertElementAt(jMethodSig, i);
added = true;
break;
}
}
//-- compare names
if (jMethodSig.getName().compareTo(tmp.getName()) < 0) {
methods.insertElementAt(jMethodSig, i);
added = true;
break;
}
}
//-- END SORT
if (!added) methods.addElement(jMethodSig);
//-- check parameter packages to make sure we have them
//-- in our import list
String[] pkgNames = jMethodSig.getParameterClassNames();
for (int i = 0; i < pkgNames.length; i++) {
addImport(pkgNames[i]);
}
//-- check return type to make sure it's included in the
//-- import list
JType jType = jMethodSig.getReturnType();
if (jType != null) {
while (jType.isArray())
jType = jType.getComponentType();
if (!jType.isPrimitive())
addImport(jType.getName());
}
//-- check exceptions
JClass[] exceptions = jMethodSig.getExceptions();
for (int i = 0; i < exceptions.length; i++) {
addImport(exceptions[i].getName());
}
} //-- addMethod
*/
/**
* Returns the field with the given name, or null if no field
* was found with the given name.
*
* @param name the name of the field to return.
* @return the field with the given name, or null if no field
* was found with the given name.
*/
public abstract JField getField( String name );
/**
* Returns an array of all the JFields of this JStructure
*
* @return an array of all the JFields of this JStructure
*/
public abstract JField[] getFields();
/**
* Returns the name of the file that this JStructure would be
* printed to, given a call to #print.
*
* @param destDir the destination directory. This may be null.
* @return the name of the file that this JInterface would be
* printed as, given a call to #print.
*/
public String getFilename( String destDir )
{
String filename = getLocalName() + ".java";
//-- Convert Java package to path string
String javaPackagePath = "";
if ( ( packageName != null ) && ( packageName.length() > 0 ) )
{
javaPackagePath = packageName.replace( '.', File.separatorChar );
}
//-- Create fully qualified path (including 'destDir') to file
File pathFile;
if ( destDir == null )
pathFile = new File( javaPackagePath );
else
pathFile = new File( destDir, javaPackagePath );
if ( !pathFile.exists() )
{
pathFile.mkdirs();
}
//-- Prefix filename with path
if ( pathFile.toString().length() > 0 )
filename = pathFile.toString() + File.separator + filename;
return filename;
} //-- getFilename
/**
* Returns the JComment header to display at the top of the source file
* for this JStructure, or null if no header was set.
*
* @return the JComment header or null if none exists.
*/
public JComment getHeader()
{
return this.header;
} //-- getHeader
/**
* Returns an Enumeration of imported package and
* class names for this JStructure.
*
* @return the Enumeration of imports. May be empty.
*/
public Enumeration getImports()
{
return imports.elements();
} //-- getImports
/**
* Returns an Enumeration of interface names that this
* JStructure inherits from.
*
* @return the Enumeration of interface names for this
* JStructure. May be empty.
*/
public Enumeration getInterfaces()
{
return interfaces.elements();
} //-- getInterfaces
/**
* Returns the Java Doc comment for this JStructure
*
* @return the JDocComment for this JStructure
*/
public JDocComment getJDocComment()
{
return jdc;
} //-- getJDocComment
/**
* Returns an array of all the JMethodSignatures of this JInterface.
*
* @return an array of all the JMethodSignatures of this JInterface.
*/
/*
public JMethodSignature[] getMethods() {
JMethodSignature[] marray = new JMethodSignature[methods.size()];
methods.copyInto(marray);
return marray;
} //-- getMethods
*/
/**
* Returns the JMethodSignature with the given name,
* and occuring at or after the given starting index.
*
* @param name the name of the JMethodSignature to return.
* @param startIndex the starting index to begin searching
* from.
* @return the JMethodSignature, or null if not found.
*/
/*
public JMethodSignature getMethod(String name, int startIndex) {
for (int i = startIndex; i < methods.size(); i++) {
JMethodSignature jMethod = (JMethodSignature)methods.elementAt(i);
if (jMethod.getName().equals(name)) return jMethod;
}
return null;
} //-- getMethod
*/
/**
* Returns the JMethodSignature at the given index.
*
* @param index the index of the JMethodSignature to return.
* @return the JMethodSignature at the given index.
*/
/*
public JMethodSignature getMethod(int index) {
return (JMethodSignature)methods.elementAt(index);
} //-- getMethod
*/
/**
* Returns the JModifiers which allows the qualifiers to be changed.
*
* @return the JModifiers for this JStructure.
*/
public JModifiers getModifiers()
{
return modifiers;
} //-- getModifiers
/**
* Returns the name of the package that this JStructure is a member
* of.
*
* @return the name of the package that this JStructure is a member
* of, or null if there is no current package name defined.
*/
public String getPackageName()
{
return this.packageName;
} //-- getPackageName
/**
* Returns the name of the interface.
*
* @param stripPackage a boolean that when true indicates that only
* the local name (no package) should be returned.
* @return the name of the class.
*/
public String getName( boolean stripPackage )
{
String name = super.getName();
if ( stripPackage )
{
int period = name.lastIndexOf( "." );
if ( period > 0 )
name = name.substring( period + 1 );
}
return name;
} //-- getName
/**
* Returns true if the given classname exists in the imports
* of this JStructure
*
* @param classname the class name to check for
* @return true if the given classname exists in the imports list
*/
public boolean hasImport( String classname )
{
return imports.contains( classname );
} //-- hasImport
public boolean removeImport( String className )
{
boolean result = false;
if ( className == null ) return result;
if ( className.length() == 0 ) return result;
result = imports.removeElement( className );
return result;
} //-- removeImport
public boolean isAbstract()
{
return modifiers.isAbstract();
}
public static boolean isValidClassName( String name )
{
if ( name == null ) return false;
//-- ignore package information, for now
int period = name.lastIndexOf( "." );
if ( period > 0 )
name = name.substring( period + 1 );
return JNaming.isValidJavaIdentifier( name );
} //-- isValidClassName
/**
* Prints the source code for this JStructure in the current
* working directory. Sub-directories will be created if necessary
* for the package.
*/
public void print()
{
print( (String) null, (String) null );
} //-- printSrouce
/**
* Prints the source code for this JStructure to the destination
* directory. Sub-directories will be created if necessary for the
* package.
*
* @param lineSeparator the line separator to use at the end of each line.
* If null, then the default line separator for the runtime platform will
* be used.
*/
public void print( String destDir, String lineSeparator )
{
// String name = getLocalName();
//-- open output file
String filename = getFilename( destDir );
File file = new File( filename );
JSourceWriter jsw = null;
try
{
jsw = new JSourceWriter( WriterFactory.newPlatformWriter( file ) );
}
catch ( java.io.IOException ioe )
{
System.out.println( "unable to create class file: " + filename );
return;
}
if ( lineSeparator == null )
{
lineSeparator = System.getProperty( "line.separator" );
}
jsw.setLineSeparator( lineSeparator );
print( jsw );
jsw.close();
} //-- print
/**
* Prints the source code for this JStructure to the given
* JSourceWriter.
*
* @param jsw the JSourceWriter to print to.
*/
public abstract void print( JSourceWriter jsw );
/**
* A utility method that prints the header to the given
* JSourceWriter
*
* @param jsw the JSourceWriter to print to.
*/
public void printHeader( JSourceWriter jsw )
{
if ( jsw == null )
{
throw new IllegalArgumentException( "argument 'jsw' should not be null." );
}
//-- write class header
JComment header = getHeader();
if ( header != null )
header.print( jsw );
else
{
jsw.writeln( "/*" );
jsw.writeln( " * " + DEFAULT_HEADER );
jsw.writeln( " */" );
}
jsw.writeln();
jsw.flush();
} //-- printHeader
/**
* A utility method that prints the imports to the given
* JSourceWriter
*
* @param jsw the JSourceWriter to print to.
*/
public void printImportDeclarations( JSourceWriter jsw )
{
if ( jsw == null )
{
throw new IllegalArgumentException( "argument 'jsw' should not be null." );
}
//-- print imports
if ( imports.size() > 0 )
{
jsw.writeln( " //---------------------------------/" );
jsw.writeln( " //- Imported classes and packages -/" );
jsw.writeln( "//---------------------------------/" );
jsw.writeln();
Enumeration e = imports.elements();
while ( e.hasMoreElements() )
{
jsw.write( "import " );
jsw.write( e.nextElement() );
jsw.writeln( ';' );
}
jsw.writeln();
jsw.flush();
}
} //-- printImportDeclarations
/**
* A utility method that prints the packageDeclaration to
* the given JSourceWriter
*
* @param jsw the JSourceWriter to print to.
*/
public void printPackageDeclaration( JSourceWriter jsw )
{
if ( jsw == null )
{
throw new IllegalArgumentException( "argument 'jsw' should not be null." );
}
//-- print package name
if ( ( packageName != null ) && ( packageName.length() > 0 ) )
{
jsw.write( "package " );
jsw.write( packageName );
jsw.writeln( ';' );
jsw.writeln();
}
jsw.flush();
} //-- printPackageDeclaration
/**
* Prints the source code for this JStructure to the given
* JSourceWriter.
*
* @param jsw the JSourceWriter to print to.
*
public abstract void print(JSourceWriter jsw);
StringBuffer buffer = new StringBuffer();
printHeader();
printPackageDeclaration();
printImportDeclarations();
//------------/
//- Java Doc -/
//------------/
jdc.print(jsw);
//-- print class information
//-- we need to add some JavaDoc API adding comments
buffer.setLength(0);
if (modifiers.isPrivate()) {
buffer.append("private ");
}
else if (modifiers.isPublic()) {
buffer.append("public ");
}
if (modifiers.isAbstract()) {
buffer.append("abstract ");
}
buffer.append("interface ");
buffer.append(getLocalName());
buffer.append(' ');
if (interfaces.size() > 0) {
boolean endl = false;
if (interfaces.size() > 1) {
jsw.writeln(buffer.toString());
buffer.setLength(0);
endl = true;
}
buffer.append("extends ");
for (int i = 0; i < interfaces.size(); i++) {
if (i > 0) buffer.append(", ");
buffer.append(interfaces.elementAt(i));
}
if (endl) {
jsw.writeln(buffer.toString());
buffer.setLength(0);
}
else buffer.append(' ');
}
buffer.append('{');
jsw.writeln(buffer.toString());
buffer.setLength(0);
jsw.writeln();
jsw.indent();
//-- print method signatures
if (methods.size() > 0) {
jsw.writeln();
jsw.writeln(" //-----------/");
jsw.writeln(" //- Methods -/");
jsw.writeln("//-----------/");
jsw.writeln();
}
for (int i = 0; i < methods.size(); i++) {
JMethodSignature signature = (JMethodSignature) methods.elementAt(i);
signature.print(jsw);
jsw.writeln(';');
}
jsw.unindent();
jsw.writeln('}');
jsw.flush();
jsw.close();
} //-- printSource
*/
/**
* Sets the header comment for this JStructure
*
* @param comment the comment to display at the top of the source file
* when printed
*/
public void setHeader( JComment comment )
{
this.header = comment;
} //-- setHeader
/**
* Allows changing the package name of this JStructure
*
* @param packageName the package name to use
* @deprecated removed in future version of javasource
*/
public void setPackageName( String packageName )
{
this.packageName = packageName;
changePackage( packageName );
} //-- setPackageName
//---------------------/
//- Protected Methods -/
//---------------------/
protected int getInterfaceCount()
{
return interfaces.size();
}
/**
* Prints the given source string to the JSourceWriter using the given prefix at
* the beginning of each new line.
*
* @param prefix the prefix for each new line.
* @param source the source code to print
* @param jsw the JSourceWriter to print to.
*/
protected static void printlnWithPrefix( String prefix, String source, JSourceWriter jsw )
{
jsw.write( prefix );
if ( source == null ) return;
char[] chars = source.toCharArray();
int lastIdx = 0;
for ( int i = 0; i < chars.length; i++ )
{
char ch = chars[i];
if ( ch == '\n' )
{
//-- free buffer
jsw.write( chars, lastIdx, ( i - lastIdx ) + 1 );
lastIdx = i + 1;
if ( i < chars.length )
{
jsw.write( prefix );
}
}
}
//-- free buffer
if ( lastIdx < chars.length )
{
jsw.write( chars, lastIdx, chars.length - lastIdx );
}
jsw.writeln();
} //-- printlnWithPrefix
/**
* Returns the package name from the given class name
*/
protected static String getPackageFromClassName( String className )
{
int idx = -1;
if ( ( idx = className.lastIndexOf( '.' ) ) > 0 )
{
return className.substring( 0, idx );
}
return null;
} //-- getPackageFromClassName
/**
* @return the annotations
*/
public JAnnotations getAnnotations()
{
return annotations;
}
/**
* @param annotation the annotation to append
*/
public void appendAnnotation( String annotation )
{
if ( annotations == null )
{
annotations = new JAnnotations();
}
annotations.appendAnnotation( annotation );
}
/**
* @param annotations the annotations to set
*/
public void setAnnotations( JAnnotations annotations )
{
this.annotations = annotations;
}
} //-- JStructure
././@LongLink 0000000 0000000 0000000 00000000173 00000000000 011566 L ustar root root modello-1.1/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/javasource/JSourceCode.java modello-1.1/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/javas0000644 0001750 0001750 00000023162 11123452344 032674 0 ustar mkoch mkoch /**
* Redistribution and use of this software and associated documentation
* ("Software"), with or without modification, are permitted provided
* that the following conditions are met:
*
* 1. Redistributions of source code must retain copyright
* statements and notices. Redistributions must also contain a
* copy of this document.
*
* 2. Redistributions in binary form must reproduce the
* above copyright notice, this list of conditions and the
* following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* 3. The name "Exolab" must not be used to endorse or promote
* products derived from this Software without prior written
* permission of Intalio, Inc. For written permission,
* please contact info@codehaus.org.
*
* 4. Products derived from this Software may not be called "Exolab"
* nor may "Exolab" appear in their names without prior written
* permission of Intalio, Inc. Exolab is a registered
* trademark of Intalio, Inc.
*
* 5. Due credit should be given to the Exolab Project
* (http://www.codehaus.org/).
*
* THIS SOFTWARE IS PROVIDED BY INTALIO, INC. AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT
* NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
* INTALIO, INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Copyright 1999-2001 (C) Intalio, Inc. All Rights Reserved.
*
* $Id: JSourceCode.java 1040 2008-12-21 14:38:28Z hboutemy $
*/
package org.codehaus.modello.plugin.java.javasource;
/*
* Copyright (c) 2004, Codehaus.org
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is furnished to do
* so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
import org.codehaus.modello.ModelloRuntimeException;
import java.util.Vector;
/**
* A class for holding in-memory Java source code.
*
* @author Keith Visco
* @version $Revision: 1040 $ $Date: 2008-12-21 15:38:28 +0100 (So, 21. Dez 2008) $
**/
public class JSourceCode
{
/**
* A list of JCodeStatements
**/
private Vector source = null;
/**
* The indent size
**/
private short indentSize = 4;
/**
* The current indent size
**/
private short currentIndent = indentSize;
/**
* Creates an empty JSourceCode
**/
public JSourceCode()
{
super();
source = new Vector();
} //-- JSourceCode
/**
* Creates a JSourceCode and adds the given String
* to it's contents
* @param sourceCode the source to add
**/
public JSourceCode( String sourceCode )
{
this();
this.source.addElement( new JCodeStatement( sourceCode, currentIndent ) );
} //-- JSourceCode
/**
* Adds the given statement to this JSourceCode. The statement
* will be added on a new line.
* @param statement the statement to add
**/
public void add( String statement )
{
JCodeStatement jcs = new JCodeStatement( statement, currentIndent );
source.addElement( jcs );
} //-- add
/**
* Adds the given statement to this JSourceCode. The statement
* will be added on a new line.
* @param statement the statement to add
* @param the indentSize is the size of the indentation to use
* when printing this JSourceCode
* @see #print
* @deprecated this method is not here any mode in castor codegen 1.3rc1
**/
public void add( String statement, short indentSize )
{
JCodeStatement jcs = new JCodeStatement( statement, indentSize );
source.addElement( jcs );
} //-- add
/**
* Adds the given statement to this JSourceCode. The statement
* will be added on a new line and added with increased indent.
* This is a convenience method for the sequence
*
* indent();
* add(statement);
* unindent();
*
* @param statement the statement to add
**/
public void addIndented( String statement )
{
indent();
JCodeStatement jcs = new JCodeStatement( statement, currentIndent );
source.addElement( jcs );
unindent();
} //-- add
/**
* Appends the given String to the last line in this
* JSourceCode
* @param segment the String to append
**/
public void append( String segment )
{
if ( source.isEmpty() )
add( segment );
else
{
JCodeStatement jcs = (JCodeStatement) source.lastElement();
jcs.append( segment );
}
} //-- append(String)
/**
* Clears all the code statements from this JSourceCode
**/
public void clear()
{
source.removeAllElements();
} //-- clear();
/**
* Copies the contents of this JSourceCode into the given JSourceCode
* @param jsc the JSourceCode to copy this JSourceCode into
**/
public void copyInto( JSourceCode jsc )
{
for ( int i = 0; i < source.size(); i++ )
{
jsc.addCodeStatement( (JCodeStatement) source.elementAt( i ) );
}
} //-- copyInto
/**
* Increases the current indent level by 1
**/
public void indent()
{
currentIndent += indentSize;
} //-- indent();
/**
* Returns true if this JSourceCode is empty (ie. no source).
* @return true if this JSourceCode is empty.
**/
public boolean isEmpty()
{
return source.isEmpty();
} //-- isEmpty
/**
* Prints this JSourceCode to the given JSourceWriter
* @param jsw the JSourceWriter to print to
**/
public void print( JSourceWriter jsw )
{
for ( int i = 0; i < source.size(); i++ )
jsw.writeln( source.elementAt( i ).toString() );
} //-- print
/**
* Decreases the indent level by 1
**/
public void unindent()
{
if ( currentIndent == 0 )
{
throw new ModelloRuntimeException( "Cannot unindent: current indent is 0." );
}
currentIndent -= indentSize;
} //-- unindent
/**
* Returns the String representation of this JSourceCode
* @return the String representation of this JSourceCode
**/
public String toString()
{
StringBuffer sb = new StringBuffer();
String lineSeparator = System.getProperty( "line.separator" );
for ( int i = 0; i < source.size(); i++ )
{
sb.append( source.elementAt( i ).toString() );
sb.append( lineSeparator );
}
return sb.toString();
} //-- toString
/**
* Adds the given JCodeStatement to this JSourceCode
* @param jcs the JCodeStatement to add
**/
private void addCodeStatement( JCodeStatement jcs )
{
short indent = (short) ( jcs.getIndent() + currentIndent - JCodeStatement.DEFAULT_INDENTSIZE );
source.addElement( new JCodeStatement( jcs.getStatement(), indent ) );
} //-- addCodeStatement(JCodeStatement)
} //-- JSourceCode
/**
* Represents a line of code, used by JSourceCode class
* @author Keith Visco
**/
class JCodeStatement
{
private StringBuffer value = null;
static public short DEFAULT_INDENTSIZE = 4;
private short indentSize = DEFAULT_INDENTSIZE;
JCodeStatement()
{
super();
value = new StringBuffer();
} //-- JCodeStatement
JCodeStatement( String statement )
{
this();
this.value.append( statement );
} //-- JCodeStatement
JCodeStatement( String statement, short indentSize )
{
this( statement );
this.indentSize = indentSize;
} //-- JCodeStatement
void append( String segment )
{
value.append( segment );
}
short getIndent()
{
return indentSize;
} //-- getIndent
String getStatement()
{
return value.toString();
} //-- getStatement
public String toString()
{
if ( value.length() == 0 )
{
return "";
}
StringBuffer sb = new StringBuffer( indentSize + value.length() );
for ( int i = 0; i < indentSize; i++ ) sb.append( ' ' );
sb.append( value.toString() );
return sb.toString();
}
} //-- JCodeStatement
././@LongLink 0000000 0000000 0000000 00000000167 00000000000 011571 L ustar root root modello-1.1/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/javasource/JNaming.java modello-1.1/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/javas0000644 0001750 0001750 00000013233 10367232700 032673 0 ustar mkoch mkoch /**
* Redistribution and use of this software and associated documentation
* ("Software"), with or without modification, are permitted provided
* that the following conditions are met:
*
* 1. Redistributions of source code must retain copyright
* statements and notices. Redistributions must also contain a
* copy of this document.
*
* 2. Redistributions in binary form must reproduce the
* above copyright notice, this list of conditions and the
* following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* 3. The name "Exolab" must not be used to endorse or promote
* products derived from this Software without prior written
* permission of Intalio, Inc. For written permission,
* please contact info@codehaus.org.
*
* 4. Products derived from this Software may not be called "Exolab"
* nor may "Exolab" appear in their names without prior written
* permission of Intalio, Inc. Exolab is a registered
* trademark of Intalio, Inc.
*
* 5. Due credit should be given to the Exolab Project
* (http://www.codehaus.org/).
*
* THIS SOFTWARE IS PROVIDED BY INTALIO, INC. AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT
* NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
* INTALIO, INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Copyright 1999-2000 (C) Intalio, Inc. All Rights Reserved.
*
* $Id: JNaming.java 555 2006-01-29 21:38:08Z jvanzyl $
*/
package org.codehaus.modello.plugin.java.javasource;
/*
* Copyright (c) 2004, Codehaus.org
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is furnished to do
* so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
/**
* A utility class used to validate identifiers
* and class names
* @author Keith Visco
* @version $Revision: 555 $ $Date: 2006-01-29 22:38:08 +0100 (So, 29. Jan 2006) $
**/
class JNaming
{
private static final String[] keywords = {
"abstract",
"boolean",
"break",
"byte",
"case",
"catch",
"char",
"class",
"const",
"continue",
"default",
"do",
"double",
"else",
"extends",
"false",
"final",
"finally",
"float",
"for",
"goto",
"if",
"implements",
"import",
"instanceof",
"int",
"interface",
"long",
"native",
"new",
"null",
"package",
"private",
"protected",
"public",
"return",
"short",
"static",
"super",
"switch",
"synchronized",
"this",
"throw",
"throws",
"transient",
"true",
"try",
"void",
"volatile",
"while"
}; //-- keywords
private JNaming()
{
super();
}
/**
* Returns true if the given String is a Java keyword which
* will cause a problem when used as a variable name
**/
public static boolean isKeyword( String name )
{
if ( name == null ) return false;
for ( int i = 0; i < keywords.length; i++ )
{
if ( keywords[i].equals( name ) ) return true;
}
return false;
} //-- isKeyword
/**
* Returns true if the given String matches the
* production of a valid Java identifier
*
* @param string, the String to check the production of
* @return true if the given String matches the
* production of a valid Java name, otherwise false
**/
public static boolean isValidJavaIdentifier( String string )
{
if ( ( string == null ) || ( string.length() == 0 ) )
return false;
char[] chars = string.toCharArray();
//-- make sure starting character is valid
if ( !Character.isJavaIdentifierStart( chars[0] ) )
return false;
for ( int i = 1; i < chars.length; i++ )
{
if ( !Character.isJavaIdentifierPart( chars[i] ) )
return false;
}
if ( isKeyword( string ) ) return false;
return true;
} //-- isValidJavaIdentifier
} //-- JNaming ././@LongLink 0000000 0000000 0000000 00000000170 00000000000 011563 L ustar root root modello-1.1/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/javasource/JComment.java modello-1.1/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/javas0000644 0001750 0001750 00000026440 10367232700 032677 0 ustar mkoch mkoch /**
* Redistribution and use of this software and associated documentation
* ("Software"), with or without modification, are permitted provided
* that the following conditions are met:
*
* 1. Redistributions of source code must retain copyright
* statements and notices. Redistributions must also contain a
* copy of this document.
*
* 2. Redistributions in binary form must reproduce the
* above copyright notice, this list of conditions and the
* following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* 3. The name "Exolab" must not be used to endorse or promote
* products derived from this Software without prior written
* permission of Intalio, Inc. For written permission,
* please contact info@codehaus.org.
*
* 4. Products derived from this Software may not be called "Exolab"
* nor may "Exolab" appear in their names without prior written
* permission of Intalio, Inc. Exolab is a registered
* trademark of Intalio, Inc.
*
* 5. Due credit should be given to the Exolab Project
* (http://www.codehaus.org/).
*
* THIS SOFTWARE IS PROVIDED BY INTALIO, INC. AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT
* NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
* INTALIO, INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Copyright 1999 (C) Intalio, Inc. All Rights Reserved.
*
* $Id: JComment.java 555 2006-01-29 21:38:08Z jvanzyl $
*/
package org.codehaus.modello.plugin.java.javasource;
/*
* Copyright (c) 2004, Codehaus.org
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is furnished to do
* so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
/**
* A class that represents a Java comment.
* @author Keith Visco
* @version $Revision: 555 $ $Date: 2006-01-29 22:38:08 +0100 (So, 29. Jan 2006) $
**/
public class JComment
{
/**
* The auto style, allows this JComment to automatically
* choose a style for this comment
**/
public static final short AUTO_STYLE = 0;
/**
* The block comment style: \/* *\/
**/
public static final short BLOCK_STYLE = 1;
/**
* The line comment style: \/\/
**/
public static final short LINE_STYLE = 2;
/**
* The header style, similiar to block, but with an '*'
* at the start of each line.
**/
public static final short HEADER_STYLE = 3;
/**
* Similiar to HEADER_STYLE, but starts with: \/**
**/
public static final short JAVADOC_STYLE = 4;
private static final String START_BLOCK = "/*";
private static final String END_BLOCK = " */";
private static final String START_JAVADOC = "/**";
private static final String END_JAVADOC = " */";
private static final String ASTERIX_PREFIX = " * ";
private static final String LINE_COMMENT_PREFIX = "// ";
private static final String SPACE_PREFIX = " ";
/**
* The style of this comment
**/
private short style = AUTO_STYLE;
/**
* The main comment for this JDocComment
**/
private StringBuffer _comment = null;
/**
* The maximum number of characters per line
**/
protected static final int MAX_LENGTH = 65;
/**
* Creates a new Java Comment
**/
public JComment()
{
super();
_comment = new StringBuffer();
} //-- JComment
/**
* Creates a new Java comment with the given style
**/
public JComment( short style )
{
this();
this.style = style;
} //-- JComment
/**
* Appends the comment String to this JDocComment
* @param comment the comment to append
**/
public void appendComment( String comment )
{
_comment.append( comment );
} //-- appendComment
/**
* prints this JComment using the given JSourceWriter
* @param jsw the JSourceWriter to print to
**/
public void print( JSourceWriter jsw )
{
if ( jsw == null ) return; //-- nothing to do
LineFormatter formatter = null;
//-- calculate comment length
short currentIndent = jsw.getIndentSize();
int maxLength = MAX_LENGTH - currentIndent;
//-- a simple to check to make sure we have some room
//-- to print the comment
if ( maxLength <= 17 ) maxLength = MAX_LENGTH / 2;
short resolvedStyle = style;
if ( style == AUTO_STYLE )
{
//-- estimation of number of lines
int nbrLines = _comment.length() / maxLength;
if ( nbrLines > 2 )
resolvedStyle = BLOCK_STYLE;
else
resolvedStyle = LINE_STYLE;
}
//-- start comment
String prefix = null;
String start = null;
String end = null;
switch ( resolvedStyle )
{
case BLOCK_STYLE:
start = START_BLOCK;
end = END_BLOCK;
prefix = SPACE_PREFIX;
break;
case HEADER_STYLE:
start = START_BLOCK;
end = END_BLOCK;
prefix = ASTERIX_PREFIX;
break;
case JAVADOC_STYLE:
start = START_JAVADOC;
end = END_JAVADOC;
prefix = ASTERIX_PREFIX;
break;
default: //-- LINE
prefix = LINE_COMMENT_PREFIX;
break;
}
if ( start != null ) jsw.writeln( start );
//-- print main comment
formatter = new LineFormatter( _comment.toString(), maxLength, prefix );
while ( formatter.hasMoreLines() )
{
jsw.writeln( formatter.nextLine() );
}
if ( end != null ) jsw.writeln( end );
jsw.flush();
} //-- print
/**
* Sets the comment String of this JDocComment
* @param comment the comment String of this JDocComment
**/
public void setComment( String comment )
{
_comment.setLength( 0 );
_comment.append( comment );
} //-- setComment
/**
* Sets the style for this JComment
* @param style the style to use for this JComment
**/
public void setStyle( short style )
{
this.style = style;
} //-- setStyle
/**
* Returns the String representation of this Java Doc Comment
* @return the String representation of this Java Doc Comment
**/
public String toString()
{
return "";
} //-- toString
} //-- JComment
/**
* Formats a given String for use within a Java comment
* @author Keith Visco
**/
class LineFormatter
{
String comment = null;
int maxLength = 65;
int offset = 0;
int length = 0;
String prefix = null;
private StringBuffer sb = null;
/**
* Creates a LineFormatter for the given comment
* @param comment the String to format
**/
LineFormatter( String comment )
{
this.comment = comment;
if ( comment != null ) this.length = comment.length();
sb = new StringBuffer();
} //-- LineFormatter
/**
* Creates a new LineFormatter for the given comment
* @param comment the String to format
* @param maxLength the maximum number of characters per line
**/
LineFormatter( String comment, int maxLength )
{
this( comment, maxLength, null );
} //-- LineFormatter
/**
* Creates a new LineFormatter for the given comment
* @param comment the String to format
* @param maxLength the maximum number of characters per line
* @param prefix a prefix to append to the beginning of each line
**/
LineFormatter( String comment, int maxLength, String prefix )
{
this( comment );
this.maxLength = maxLength;
this.prefix = prefix;
} //-- LineFormatter
boolean hasMoreLines()
{
if ( comment == null ) return false;
return ( offset < length );
} //-- isFinished
String nextLine()
{
if ( comment == null ) return null;
if ( offset >= length ) return null;
sb.setLength( 0 );
if ( prefix != null ) sb.append( prefix );
int max = offset + maxLength;
if ( max > this.length ) max = this.length;
int index = offset;
int breakable = offset;
for ( ; index < max; index++ )
{
char ch = comment.charAt( index );
if ( isNewLine( ch ) )
{
sb.append( comment.substring( offset, index ) );
offset = index + 1;
return sb.toString();
}
if ( isWhitespace( ch ) ) breakable = index;
}
if ( index < length - 1 )
{
//-- if we could not find a breakable character, we must look
//-- ahead
if ( offset == breakable )
{
while ( index < length )
{
if ( isBreakable( comment.charAt( index ) ) ) break;
++index;
}
}
else
index = breakable;
}
sb.append( comment.substring( offset, index ) );
offset = index + 1;
return sb.toString();
} //-- getNextLine
/**
* Sets the prefix that should be appended to the beginning of
* each line
* @param prefix the prefix for this LineFormatter
**/
void setPrefix( String prefix )
{
this.prefix = prefix;
} //-- setPrefix
private boolean isBreakable( char ch )
{
return ( isWhitespace( ch ) || isNewLine( ch ) );
}
private boolean isWhitespace( char ch )
{
return ( ( ch == ' ' ) || ( ch == '\t' ) );
} //-- isWhitespace
private boolean isNewLine( char ch )
{
return ( ( ch == '\n' ) || ( ch == '\r' ) );
} //-- isNewLineChar
} //-- LineFormatter
././@LongLink 0000000 0000000 0000000 00000000174 00000000000 011567 L ustar root root modello-1.1/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/javasource/JAnnotations.java modello-1.1/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/javas0000644 0001750 0001750 00000002413 11232155760 032673 0 ustar mkoch mkoch package org.codehaus.modello.plugin.java.javasource;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class JAnnotations
{
private List/*String*/ annotations;
public JAnnotations()
{
this.annotations = new ArrayList();
}
public void appendAnnotation( String annotation )
{
annotations.add( annotation );
}
/**
* Returns the String representation of this JAnnotations
* @return the String representation of this JAnnotations
**/
public String toString()
{
StringBuffer sb = new StringBuffer();
Iterator iterator = annotations.iterator();
while ( iterator.hasNext() )
{
sb.append( iterator.next().toString() );
if ( iterator.hasNext() )
{
sb.append( ' ' );
}
}
return sb.toString();
} //-- toString
/**
* prints this Annotations using the given JSourceWriter
*
* @param jsw the JSourceWriter to print to
*/
public void print( JSourceWriter jsw )
{
Iterator iterator = annotations.iterator();
while ( iterator.hasNext() )
{
jsw.writeln( iterator.next().toString() );
}
} // -- print
}
././@LongLink 0000000 0000000 0000000 00000000171 00000000000 011564 L ustar root root modello-1.1/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/javasource/JNamedMap.java modello-1.1/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/javas0000644 0001750 0001750 00000017013 10367232700 032673 0 ustar mkoch mkoch /**
* Redistribution and use of this software and associated documentation
* ("Software"), with or without modification, are permitted provided
* that the following conditions are met:
*
* 1. Redistributions of source code must retain copyright
* statements and notices. Redistributions must also contain a
* copy of this document.
*
* 2. Redistributions in binary form must reproduce the
* above copyright notice, this list of conditions and the
* following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* 3. The name "Exolab" must not be used to endorse or promote
* products derived from this Software without prior written
* permission of Intalio, Inc. For written permission,
* please contact info@codehaus.org.
*
* 4. Products derived from this Software may not be called "Exolab"
* nor may "Exolab" appear in their names without prior written
* permission of Intalio, Inc. Exolab is a registered
* trademark of Intalio, Inc.
*
* 5. Due credit should be given to the Exolab Project
* (http://www.codehaus.org/).
*
* THIS SOFTWARE IS PROVIDED BY INTALIO, INC. AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT
* NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
* INTALIO, INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Copyright 1999 (C) Intalio, Inc. All Rights Reserved.
*
* $Id: JNamedMap.java 555 2006-01-29 21:38:08Z jvanzyl $
*/
package org.codehaus.modello.plugin.java.javasource;
/*
* Copyright (c) 2004, Codehaus.org
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is furnished to do
* so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
import java.util.Vector;
/**
* A simple String to Object mapping which preserves order.
*
*
* Note:
* This class is not synchronized. So be careful. :-)
*
* @author Keith Visco
**/
public class JNamedMap
{
private Vector names = null;
private Vector objects = null;
/**
* Creates a new JNamedMap
**/
public JNamedMap()
{
names = new Vector();
objects = new Vector();
} //-- JNamedMap
/**
* Creates a new JNamedMap with the given size.
*
* @param size the initial size for this NamedMap
**/
public JNamedMap( int size )
{
names = new Vector( size );
objects = new Vector( size );
} //-- JNamedMap
/**
* Returns the Object associated with the given name.
*
* @param name the name to search for
* @return the Object associated with the given name
**/
public Object get( String name )
{
int i = indexOf( name );
if ( i >= 0 ) return objects.elementAt( i );
return null;
} //-- get
/**
* Returns the Object at the given index.
*
* @param index the index of the Object to return
* @return the Object at the given index
**/
public Object get( int index )
throws IndexOutOfBoundsException
{
return objects.elementAt( index );
} //-- get
/**
* Returns the name associated with the given Object
*
* @param obj the Object to search for
* @return the name of the given Object
**/
public String getNameByObject( Object obj )
{
int i = objects.indexOf( obj );
if ( i >= 0 ) return (String) names.elementAt( i );
return null;
} //-- getNameByObject
/**
* Return a Vector of names
*
* @return a Vector of names
**/
public Vector getNames()
{
return (Vector) names.clone();
} //-- getNames
/**
* Return a Vector of Objects
*
* @return a Vector of Objects
**/
public Vector getObjects()
{
return (Vector) objects.clone();
} //-- getObjects
/**
* Returns the index of the Object which has been
* mapped (associated) with the given name
*
* @return the index of the Object which has been mapped (associated)
* to the given name
**/
public int indexOf( String name )
{
for ( int i = 0; i < names.size(); i++ )
{
String iName = (String) names.elementAt( i );
if ( iName.equals( name ) ) return i;
}
return -1;
} //-- indexOf
/**
* Maps (associates) an Object with a name
*
* @param name the name to associate with the given Object
* @param obj the Object to be mapped
**/
public void put( String name, Object obj )
{
int idx = indexOf( name );
if ( idx >= 0 )
objects.setElementAt( obj, idx );
else
{
//-- we may need some synchronization here
//-- if we are in a multithreaded environment
names.addElement( name );
objects.addElement( obj );
}
} //-- put
/**
* Removes and returns the Object located at the given index
*
* @param name the name of the Object to remove
* @return the object removed from the map.
**/
public Object remove( int index )
throws IndexOutOfBoundsException
{
Object obj = objects.elementAt( index );
objects.removeElementAt( index );
names.removeElementAt( index );
return obj;
} //-- remove
/**
* Removes and returns the Object associated with the given name
*
* @param name the name of the Object to remove
* @return the object removed from the map.
**/
public Object remove( String name )
{
Object obj = null;
int idx = indexOf( name );
if ( idx >= 0 )
{
obj = objects.elementAt( idx );
objects.removeElementAt( idx );
names.removeElementAt( idx );
}
return obj;
} //-- remove
/**
* Returns the number of Object associations currently in
* this named map
*
* @return the number of Object associations currently in
* this named map
**/
public int size()
{
return names.size();
} //-- size
} //-- JNamedMap ././@LongLink 0000000 0000000 0000000 00000000166 00000000000 011570 L ustar root root modello-1.1/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/javasource/JClass.java modello-1.1/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/javas0000644 0001750 0001750 00000066453 11231735057 032713 0 ustar mkoch mkoch /**
* Redistribution and use of this software and associated documentation
* ("Software"), with or without modification, are permitted provided
* that the following conditions are met:
*
* 1. Redistributions of source code must retain copyright
* statements and notices. Redistributions must also contain a
* copy of this document.
*
* 2. Redistributions in binary form must reproduce the
* above copyright notice, this list of conditions and the
* following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* 3. The name "Exolab" must not be used to endorse or promote
* products derived from this Software without prior written
* permission of Intalio, Inc. For written permission,
* please contact info@codehaus.org.
*
* 4. Products derived from this Software may not be called "Exolab"
* nor may "Exolab" appear in their names without prior written
* permission of Intalio, Inc. Exolab is a registered
* trademark of Intalio, Inc.
*
* 5. Due credit should be given to the Exolab Project
* (http://www.codehaus.org/).
*
* THIS SOFTWARE IS PROVIDED BY INTALIO, INC. AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT
* NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
* INTALIO, INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Copyright 1999-2002 (C) Intalio, Inc. All Rights Reserved.
*
* $Id: JClass.java 1297 2009-07-23 01:17:35Z hboutemy $
*
* Contributors:
* --------------
* Keith Visco (kvisco@intalio.com) - Original Author
* Martin Skopp (skopp@riege.de) - Moved some core code into JStructure
* and revised to extend JStructure
*
*/
package org.codehaus.modello.plugin.java.javasource;
/*
* Copyright (c) 2004, Codehaus.org
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is furnished to do
* so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;
/**
* A representation of the Java Source code for a Java Class. This is
* a useful utility when creating in memory source code.
* This package was modelled after the Java Reflection API
* as much as possible to reduce the learning curve.
*
* @author Keith Visco
* @author Martin Skopp
* @version $Revision: 1297 $ $Date: 2009-07-23 03:17:35 +0200 (Do, 23. Jul 2009) $
*/
public class JClass extends JStructure
{
/**
* The list of constructors for this JClass
*/
private Vector _constructors = null;
/**
* The list of member variables (fields) of this JClass
*/
private JNamedMap _fields = null;
private Vector _innerClasses = null;
/**
* The list of methods of this JClass
*/
private Vector _methods = null;
/**
* The superclass for this JClass
*/
private String _superClass = null;
/**
* The source code for static initialization
**/
private JSourceCode _staticInitializer = new JSourceCode();
/**
* Creates a new JClass with the given name
* @param name the name of the JClass to create
* @exception java.lang.IllegalArgumentException when the given name
* is not a valid Class name
**/
public JClass( String name )
throws IllegalArgumentException
{
super( name );
_constructors = new Vector();
_fields = new JNamedMap();
_methods = new Vector();
_innerClasses = new Vector();
//-- initialize default Java doc
getJDocComment().appendComment( "Class " + getLocalName() + "." );
} //-- JClass
/**
* Adds the given Constructor to this classes list of constructors.
* The constructor must have been created with this JClass'
* createConstructor.
*
* @throws java.lang.IllegalArgumentException
*/
public void addConstructor( JConstructor constructor )
throws IllegalArgumentException
{
if ( constructor == null )
throw new IllegalArgumentException( "Constructors cannot be null" );
if ( constructor.getDeclaringClass() == this )
{
/** check signatures (add later) **/
if ( !_constructors.contains( constructor ) )
{
_constructors.addElement( constructor );
}
}
else
{
String err = "The given JConstructor was not created ";
err += "by this JClass";
throw new IllegalArgumentException( err );
}
}
/**
* Adds the given JField to this JClass
*
* @param jField, the JField to add
* @exception java.lang.IllegalArgumentException when the given
* JField has a name of an existing JField
**/
public void addField( JField jField )
throws IllegalArgumentException
{
if ( jField == null )
{
throw new IllegalArgumentException( "Class members cannot be null" );
}
String name = jField.getName();
if ( _fields.get( name ) != null )
{
String err = "duplicate name found: " + name;
throw new IllegalArgumentException( err );
}
_fields.put( name, jField );
} //-- addField
/**
* Adds the given JMember to this JClass
*
* @param jMember, the JMember to add
* @exception java.lang.IllegalArgumentException when the given
* JMember has the same name of an existing JField
* or JMethod respectively, or if the JMember is of an
* unrecognized class.
**/
public void addMember( JMember jMember )
throws IllegalArgumentException
{
if ( jMember instanceof JField )
addField( (JField) jMember );
else if ( jMember instanceof JMethod )
addMethod( (JMethod) jMember );
else
{
String error = null;
if ( jMember == null )
{
error = "the argument 'jMember' must not be null.";
}
else
{
error = "Cannot add JMember '" + jMember.getClass().getName() +
"' to JClass, unrecognized type.";
}
throw new IllegalArgumentException( error );
}
} //-- addMember
/**
* Adds the given JMethod to this JClass
*
* @param jMethod, the JMethod to add
* @param importReturnType true if we add the importReturnType to
* the class import lists. It could be useful to set it to false when
* all types are fully qualified.
* @exception java.lang.IllegalArgumentException when the given
* JMethod has the same name of an existing JMethod.
**/
public void addMethod( JMethod jMethod )
{
addMethod( jMethod, true );
}
/**
* Adds the given JMethod to this JClass
*
* @param jMethod, the JMethod to add
* @param importReturnType true if we add the importReturnType to
* the class import lists. It could be useful to set it to false when
* all types are fully qualified.
* @exception java.lang.IllegalArgumentException when the given
* JMethod has the same name of an existing JMethod.
**/
public void addMethod( JMethod jMethod, boolean importReturnType )
throws IllegalArgumentException
{
if ( jMethod == null )
{
throw new IllegalArgumentException( "Class methods cannot be null" );
}
//-- check method name and signatures *add later*
//-- keep method list sorted for esthetics when printing
//-- START SORT :-)
boolean added = false;
// short modifierVal = 0;
JModifiers modifiers = jMethod.getModifiers();
if ( modifiers.isAbstract() )
{
getModifiers().setAbstract( true );
}
for ( int i = 0; i < _methods.size(); i++ )
{
JMethod tmp = (JMethod) _methods.elementAt( i );
//-- first compare modifiers
if ( tmp.getModifiers().isPrivate() )
{
if ( !modifiers.isPrivate() )
{
_methods.insertElementAt( jMethod, i );
added = true;
break;
}
}
//-- compare names
if ( jMethod.getName().compareTo( tmp.getName() ) < 0 )
{
_methods.insertElementAt( jMethod, i );
added = true;
break;
}
}
//-- END SORT
if ( !added ) _methods.addElement( jMethod );
} //-- addMethod
/**
* Adds the given array of JMethods to this JClass
*
* @param jMethods, the JMethod[] to add
* @exception java.lang.IllegalArgumentException when any of the given
* JMethods has the same name of an existing JMethod.
**/
public void addMethods( JMethod[] jMethods )
throws IllegalArgumentException
{
for ( int i = 0; i < jMethods.length; i++ )
addMethod( jMethods[i] );
} //-- addMethods
/**
* Creates a new JConstructor and adds it to this
* JClass.
*
* @return the newly created constructor
*/
public JConstructor createConstructor()
{
return createConstructor( null );
} //-- createConstructor
/**
* Creates a new JConstructor and adds it to this
* JClass.
*
* @return the newly created constructor
*/
public JConstructor createConstructor( JParameter[] params )
{
JConstructor cons = new JConstructor( this );
if ( params != null )
{
for ( int i = 0; i < params.length; i++ )
cons.addParameter( params[i] );
}
addConstructor( cons );
return cons;
} //-- createConstructor
/**
* Creates and returns an inner-class for this JClass
*
* @param localname the name of the class (no package name)
* @return the new JClass
*/
public JClass createInnerClass( String localname )
{
if ( localname == null )
{
String err = "argument 'localname' must not be null.";
throw new IllegalArgumentException( err );
}
if ( localname.indexOf( '.' ) >= 0 )
{
String err = "The name of an inner-class must not contain a package name.";
throw new IllegalArgumentException( err );
}
String classname = getPackageName();
if ( classname != null )
{
classname = classname + "." + localname;
}
else
{
classname = localname;
}
JClass innerClass = new JInnerClass( classname );
_innerClasses.addElement( innerClass );
return innerClass;
} //-- createInnerClass
/**
* Returns the constructor at the specified index.
*
* @param index the index of the constructor to return
* @return the JConstructor at the specified index.
*/
public JConstructor getConstructor( int index )
{
return (JConstructor) _constructors.elementAt( index );
} //-- getConstructor
/**
* Returns the an array of the JConstructors contained within this JClass
*
* @return an array of JConstructor
*/
public JConstructor[] getConstructors()
{
int size = _constructors.size();
JConstructor[] jcArray = new JConstructor[size];
for ( int i = 0; i < _constructors.size(); i++ )
{
jcArray[i] = (JConstructor) _constructors.elementAt( i );
}
return jcArray;
} //-- getConstructors
/**
* Returns the member with the given name, or null if no member
* was found with the given name
* @param name the name of the member to return
* @return the member with the given name, or null if no member
* was found with the given name
**/
public JField getField( String name )
{
return (JField) _fields.get( name );
} //-- getField
/**
* Returns an array of all the JFields of this JClass
* @return an array of all the JFields of this JClass
**/
public JField[] getFields()
{
int size = _fields.size();
JField[] farray = new JField[size];
for ( int i = 0; i < size; i++ )
{
farray[i] = (JField) _fields.get( i );
}
return farray;
} //-- getFields
/**
* Returns an array of JClass (the inner classes)
* contained within this JClass.
*
* @return an array of JClass contained within this JClass
*/
public JClass[] getInnerClasses()
{
int size = _innerClasses.size();
JClass[] carray = new JClass[size];
_innerClasses.copyInto( carray );
return carray;
} //-- getInnerClasses;
/**
* Returns an array of all the JMethods of this JClass
*
* @return an array of all the JMethods of this JClass
*/
public JMethod[] getMethods()
{
int size = _methods.size();
JMethod[] marray = new JMethod[size];
for ( int i = 0; i < _methods.size(); i++ )
{
marray[i] = (JMethod) _methods.elementAt( i );
}
return marray;
} //-- getMethods
/**
* Returns the first occurrence of the method with the
* given name, starting from the specified index.
*
* @param name the name of the method to look for
* @param startIndex the starting index to begin the search
* @return the method if found, otherwise null.
*/
public JMethod getMethod( String name, int startIndex )
{
for ( int i = startIndex; i < _methods.size(); i++ )
{
JMethod jMethod = (JMethod) _methods.elementAt( i );
if ( jMethod.getName().equals( name ) ) return jMethod;
}
return null;
} //-- getMethod
/**
* Returns the JMethod located at the specified index
*
* @param index the index of the JMethod to return.
* @return the JMethod
*/
public JMethod getMethod( int index )
{
return (JMethod) _methods.elementAt( index );
} //-- getMethod
/**
* Returns the JSourceCode for the static initializer
* of this JClass
*
* @return the JSourceCode for the static initializer
* of this JClass
*/
public JSourceCode getStaticInitializationCode()
{
return _staticInitializer;
} //-- getStaticInitializationCode
/**
* Gets the super Class that this class extends
* @return superClass the super Class that this Class extends
*/
public String getSuperClass()
{
return _superClass;
} //-- getSuperClass
/**
* Prints the source code for this JClass to the given JSourceWriter
*
* @param jsw the JSourceWriter to print to. [May not be null]
*/
public void print( JSourceWriter jsw )
{
print( jsw, false );
} //-- print
/**
* Prints the source code for this JClass to the given JSourceWriter
*
* @param jsw the JSourceWriter to print to. [May not be null]
*/
public void print( JSourceWriter jsw, boolean classOnly )
{
if ( jsw == null )
{
throw new IllegalArgumentException( "argument 'jsw' should not be null." );
}
StringBuffer buffer = new StringBuffer();
if ( !classOnly )
{
printHeader( jsw );
printPackageDeclaration( jsw );
//-- get imports from inner-classes
Vector removeImports = null;
if ( _innerClasses.size() > 0 )
{
removeImports = new Vector();
for ( int i = 0; i < _innerClasses.size(); i++ )
{
JClass iClass = (JClass) _innerClasses.elementAt( i );
Enumeration e = iClass.getImports();
while ( e.hasMoreElements() )
{
String classname = (String) e.nextElement();
if ( !hasImport( classname ) )
{
addImport( classname );
removeImports.addElement( classname );
}
}
}
}
printImportDeclarations( jsw );
//-- remove imports from inner-classes, if necessary
if ( removeImports != null )
{
for ( int i = 0; i < removeImports.size(); i++ )
{
removeImport( (String) removeImports.elementAt( i ) );
}
}
}
//------------/
//- Java Doc -/
//------------/
getJDocComment().print( jsw );
JAnnotations annotations = getAnnotations();
if ( annotations != null ) annotations.print( jsw );
//-- print class information
//-- we need to add some JavaDoc API adding comments
buffer.setLength( 0 );
JModifiers modifiers = getModifiers();
if ( modifiers.isPrivate() )
{
buffer.append( "private " );
}
else if ( modifiers.isPublic() )
{
buffer.append( "public " );
}
if ( modifiers.isAbstract() )
{
buffer.append( "abstract " );
}
buffer.append( "class " );
buffer.append( getLocalName() );
jsw.writeln( buffer.toString() );
buffer.setLength( 0 );
jsw.indent();
if ( _superClass != null )
{
buffer.append( "extends " );
buffer.append( _superClass );
jsw.writeln( buffer.toString() );
buffer.setLength( 0 );
}
if ( getInterfaceCount() > 0 )
{
buffer.append( "implements " );
Enumeration e = getInterfaces();
while ( e.hasMoreElements() )
{
buffer.append( e.nextElement() );
if ( e.hasMoreElements() ) buffer.append( ", " );
}
jsw.writeln( buffer.toString() );
buffer.setLength( 0 );
}
jsw.unindent();
jsw.writeln( '{' );
jsw.indent();
//-- declare members
if ( _fields.size() > 0 )
{
jsw.writeln();
jsw.writeln( " //--------------------------/" );
jsw.writeln( " //- Class/Member Variables -/" );
jsw.writeln( "//--------------------------/" );
jsw.writeln();
}
for ( int i = 0; i < _fields.size(); i++ )
{
JField jField = (JField) _fields.get( i );
//-- print Java comment
JDocComment comment = jField.getComment();
if ( comment != null ) comment.print( jsw );
JAnnotations fieldAnnotations = jField.getAnnotations();
if ( fieldAnnotations != null ) fieldAnnotations.print( jsw );
// -- print member
jsw.write( jField.getModifiers().toString() );
jsw.write( ' ' );
JType type = jField.getType();
String typeName = type.toString();
//-- for esthetics use short name in some cases
if ( typeName.equals( toString() ) )
{
typeName = type.getLocalName();
}
jsw.write( typeName );
jsw.write( ' ' );
jsw.write( jField.getName() );
String init = jField.getInitString();
if ( init != null )
{
jsw.write( " = " );
jsw.write( init );
}
jsw.writeln( ';' );
jsw.writeln();
}
//----------------------/
//- Static Initializer -/
//----------------------/
if ( !_staticInitializer.isEmpty() )
{
jsw.writeln();
jsw.writeln( "static" );
jsw.writeln( "{" );
_staticInitializer.print( jsw );
jsw.writeln( "};" );
jsw.writeln();
}
//-- print constructors
if ( _constructors.size() > 0 )
{
jsw.writeln();
jsw.writeln( " //----------------/" );
jsw.writeln( " //- Constructors -/" );
jsw.writeln( "//----------------/" );
jsw.writeln();
}
for ( int i = 0; i < _constructors.size(); i++ )
{
JConstructor jConstructor = (JConstructor) _constructors.elementAt( i );
jConstructor.print( jsw );
jsw.writeln();
}
//-- print methods
if ( _methods.size() > 0 )
{
jsw.writeln();
jsw.writeln( " //-----------/" );
jsw.writeln( " //- Methods -/" );
jsw.writeln( "//-----------/" );
jsw.writeln();
}
for ( int i = 0; i < _methods.size(); i++ )
{
JMethod jMethod = (JMethod) _methods.elementAt( i );
jMethod.print( jsw );
jsw.writeln();
}
//-- print inner-classes
if ( _innerClasses.size() > 0 )
{
jsw.writeln();
jsw.writeln( " //-----------------/" );
jsw.writeln( " //- Inner Classes -/" );
jsw.writeln( "//-----------------/" );
jsw.writeln();
}
for ( int i = 0; i < _innerClasses.size(); i++ )
{
JClass jClass = (JClass) _innerClasses.elementAt( i );
jClass.print( jsw, true );
jsw.writeln();
}
for ( Iterator iterator = sourceCodeEntries.iterator(); iterator.hasNext(); )
{
jsw.writeln( (String) iterator.next() );
}
jsw.unindent();
jsw.writeln( '}' );
jsw.flush();
} //-- printSource
private List sourceCodeEntries = new ArrayList();
public void addSourceCode( String sourceCode )
{
sourceCodeEntries.add( sourceCode );
}
/**
* Removes the given constructor from this JClass
*
* @param constructor the JConstructor to remove
* @return true if the constructor was removed, otherwise false.
*/
public boolean removeConstructor( JConstructor constructor )
{
return _constructors.removeElement( constructor );
} //-- removeConstructor
/**
* Removes the field with the given name from this JClass
*
* @param name the name of the field to remove
**/
public JField removeField( String name )
{
if ( name == null ) return null;
JField field = (JField) _fields.remove( name );
//-- clean up imports
//-- NOT YET IMPLEMENTED
return field;
} //-- removeField
/**
* Removes the given JField from this JClass
*
* @param jField, the JField to remove
**/
public boolean removeField( JField jField )
{
if ( jField == null ) return false;
Object field = _fields.get( jField.getName() );
if ( field == jField )
{
_fields.remove( jField.getName() );
return true;
}
//-- clean up imports
//-- NOT YET IMPLEMENTED
return false;
} //-- removeField
/**
* Removes the given inner-class (JClass) from this JClass.
*
* @param jClass the JClass (inner-class) to remove.
* @return true if the JClass was removed, otherwise false.
*/
public boolean removeInnerClass( JClass jClass )
{
return _innerClasses.removeElement( jClass );
} //-- removeInnerClass
/**
* Sets the super Class that this class extends
* @param superClass the super Class that this Class extends
*/
public void setSuperClass( String superClass )
{
_superClass = superClass;
} //-- setSuperClass
/**
* Test drive method...to be removed or commented out
**/
/*public static void main( String[] args )
{
JClass testClass = new JClass( "org.acme.Test" );
testClass.addImport( "java.util.Vector" );
testClass.addMember( new JField( JType.INT, "x" ) );
JClass jcString = new JClass( "String" );
JField field = null;
field = new JField( JType.INT, "_z" );
field.getModifiers().setStatic( true );
testClass.addField( field );
testClass.getStaticInitializationCode().add( "_z = 75;" );
field = new JField( jcString, "myString" );
field.getModifiers().makePrivate();
testClass.addMember( field );
//-- create constructor
JConstructor cons = testClass.createConstructor();
cons.getSourceCode().add( "this.x = 6;" );
JMethod jMethod = new JMethod( "getX", JType.INT, null );
jMethod.setSourceCode( "return this.x;" );
testClass.addMethod( jMethod );
//-- create inner-class
JClass innerClass = testClass.createInnerClass( "Foo" );
innerClass.addImport( "java.util.Hashtable" );
innerClass.addMember( new JField( JType.INT, "_type" ) );
field = new JField( jcString, "_name" );
field.getModifiers().makePrivate();
innerClass.addMember( field );
//-- create constructor
cons = innerClass.createConstructor();
cons.getSourceCode().add( "_name = \"foo\";" );
jMethod = new JMethod( "getName", jcString, null );
jMethod.setSourceCode( "return _name;" );
innerClass.addMethod( jMethod );
testClass.print();
} //-- main
*/
final class JInnerClass extends JClass
{
JInnerClass( String name )
{
super( name );
}
/**
* Allows changing the package name of this JStructure
*
* @param packageName the package name to use
*/
public void setPackageName( String packageName )
{
throw new IllegalStateException( "Cannot change the package of an inner-class" );
} //-- setPackageName
} //-- JInnerClass
} //-- JClass
././@LongLink 0000000 0000000 0000000 00000000165 00000000000 011567 L ustar root root modello-1.1/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/javasource/JType.java modello-1.1/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/javas0000644 0001750 0001750 00000016333 11123536732 032702 0 ustar mkoch mkoch /**
* Redistribution and use of this software and associated documentation
* ("Software"), with or without modification, are permitted provided
* that the following conditions are met:
*
* 1. Redistributions of source code must retain copyright
* statements and notices. Redistributions must also contain a
* copy of this document.
*
* 2. Redistributions in binary form must reproduce the
* above copyright notice, this list of conditions and the
* following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* 3. The name "Exolab" must not be used to endorse or promote
* products derived from this Software without prior written
* permission of Intalio, Inc. For written permission,
* please contact info@codehaus.org.
*
* 4. Products derived from this Software may not be called "Exolab"
* nor may "Exolab" appear in their names without prior written
* permission of Intalio, Inc. Exolab is a registered
* trademark of Intalio, Inc.
*
* 5. Due credit should be given to the Exolab Project
* (http://www.codehaus.org/).
*
* THIS SOFTWARE IS PROVIDED BY INTALIO, INC. AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT
* NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
* INTALIO, INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Copyright 1999 (C) Intalio, Inc. All Rights Reserved.
*
* $Id: JType.java 1041 2008-12-21 22:06:18Z hboutemy $
*/
package org.codehaus.modello.plugin.java.javasource;
/*
* Copyright (c) 2004, Codehaus.org
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is furnished to do
* so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
/**
* @author Keith Visco
* @version $Revision: 1041 $ $Date: 2008-12-21 23:06:18 +0100 (So, 21. Dez 2008) $
**/
public class JType
{
public static final JType BOOLEAN = new JType( "boolean" );
public static final JType BYTE = new JType( "byte" );
public static final JType CHAR = new JType( "char" );
public static final JType DOUBLE = new JType( "double" );
public static final JType FLOAT = new JType( "float" );
public static final JType INT = new JType( "int" );
public static final JType LONG = new JType( "long" );
public static final JType SHORT = new JType( "short" );
private String name = null;
private boolean _isArray = false;
/**
* used for array types
**/
private JType _componentType = null;
/**
* Creates a new JType with the given name
* @param the name of the type
**/
public JType( String name )
{
super();
this.name = name;
} //-- JType
/**
* Creates a JType Object representing an array of the current
* JType.
* @return the new JType which is represents an array.
* @deprecated removed in javasource 1.3rc1, replaced by JArrayType
**/
public final JType createArray()
{
JType jType = new JType( getName() );
jType._isArray = true;
jType._componentType = this;
return jType;
} //-- createArray
/**
* If this JType is an array this method will returns the component type
* of the array, otherwise null will be returned.
* @return the component JType if this JType is an array, otherwise null.
**/
public JType getComponentType()
{
return _componentType;
} //-- getComponentType
public String getLocalName()
{
//-- use getName method in case it's been overloaded
String name = getName();
if ( name == null ) return null;
int idx = name.lastIndexOf( '.' );
if ( idx >= 0 )
{
name = name.substring( idx + 1 );
}
return name;
} //-- getLocalName
public String getName()
{
return this.name;
} //-- getName
/**
* Checks to see if this JType represents an array.
* @return true if this JType represents an array, otherwise false
**/
public final boolean isArray()
{
return _isArray;
}
/**
* Checks to see if this JType represents a primitive
* @return true if this JType represents a primitive, otherwise false
**/
public boolean isPrimitive()
{
return ( ( this == BOOLEAN ) ||
( this == BYTE ) ||
( this == CHAR ) ||
( this == DOUBLE ) ||
( this == FLOAT ) ||
( this == INT ) ||
( this == LONG ) ||
( this == SHORT ) );
} //-- isPrimitive
/**
* Returns the String representation of this JType, which is
* simply the name of this type.
* @return the String representation of this JType
**/
public String toString()
{
if ( _isArray )
return _componentType.toString() + "[]";
else
return this.name;
} //-- toString
//---------------------/
//- Protected methods -/
//---------------------/
/**
* Allows subtypes, such as JClass to alter the package to which
* this JType belongs
* @param newPackage the new package to which this JType belongs
*
* Note: The package name cannot be changed on a primitive type.
**/
protected void changePackage( String newPackage )
{
if ( this.name == null ) return;
if ( this.isPrimitive() ) return;
String localName = null;
int idx = name.lastIndexOf( '.' );
if ( idx >= 0 )
localName = this.name.substring( idx + 1 );
else
localName = this.name;
if ( ( newPackage == null ) || ( newPackage.length() == 0 ) )
this.name = localName;
else
this.name = newPackage + "." + localName;
} //-- changePackage
} //-- JType
././@LongLink 0000000 0000000 0000000 00000000167 00000000000 011571 L ustar root root modello-1.1/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/javasource/JMethod.java modello-1.1/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/javas0000644 0001750 0001750 00000033106 11231735057 032700 0 ustar mkoch mkoch /**
* Redistribution and use of this software and associated documentation
* ("Software"), with or without modification, are permitted provided
* that the following conditions are met:
*
* 1. Redistributions of source code must retain copyright
* statements and notices. Redistributions must also contain a
* copy of this document.
*
* 2. Redistributions in binary form must reproduce the
* above copyright notice, this list of conditions and the
* following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* 3. The name "Exolab" must not be used to endorse or promote
* products derived from this Software without prior written
* permission of Intalio, Inc. For written permission,
* please contact info@codehaus.org.
*
* 4. Products derived from this Software may not be called "Exolab"
* nor may "Exolab" appear in their names without prior written
* permission of Intalio, Inc. Exolab is a registered
* trademark of Intalio, Inc.
*
* 5. Due credit should be given to the Exolab Project
* (http://www.codehaus.org/).
*
* THIS SOFTWARE IS PROVIDED BY INTALIO, INC. AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT
* NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
* INTALIO, INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Copyright 1999-2002 (C) Intalio, Inc. All Rights Reserved.
*
* $Id: JMethod.java 1297 2009-07-23 01:17:35Z hboutemy $
*/
package org.codehaus.modello.plugin.java.javasource;
/*
* Copyright (c) 2004, Codehaus.org
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is furnished to do
* so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
import java.util.Vector;
/**
* A class which holds information about the methods of
* a JClass.
* Modelled closely after the Java Reflection API.
* This class is part of package which is used to
* create source code.
* @author Keith Visco
* @version $Revision: 1297 $ $Date: 2009-07-23 03:17:35 +0200 (Do, 23. Jul 2009) $
**/
public class JMethod implements JMember
{
/**
* The set of classes that contain this JMethod.
**/
private Vector _classes = null;
/**
* The JavaDoc comment for this JMethod. This
* will overwrite the JavaDoc for the
* JMethodSignature.
**/
private JDocComment jdc = null;
/**
* The source code for this method
**/
private JSourceCode source = null;
/**
* The signature for this method.
**/
private JMethodSignature _signature = null;
/**
* The annotation(s) for this method.
*/
private JAnnotations annotations = null;
/**
* Creates a new JMethod with the given name and "void" return type.
*
* @param name, the method name. Must not be null.
**/
public JMethod( String name )
{
this( name, null, null );
} //-- JMethod
/**
* Creates a new JMethod with the given name and returnType.
* For "void" return types, simply pass in null as the returnType.
*
* @param name, the method name. Must not be null.
* @param returnType the return type of the method. May be null.
* @deprecated removed in future version of javasource
**/
public JMethod( JType returnType, String name )
{
this( name, returnType, null );
} //-- JMethod
/**
* Creates a new JMethod with the given name and returnType.
* For "void" return types, simply pass in null as the returnType.
*
* @param name, the method name. Must not be null.
* @param returnType the return type of the method. May be null.
* @param returnDoc Javadoc comment for the @return annotation. If
* null, a default (and mostly useless) javadoc comment will be
* generated.
**/
public JMethod( final String name, final JType returnType, final String returnDoc )
{
if ( ( name == null ) || ( name.length() == 0 ) )
{
String err = "The method name must not be null or zero-length";
throw new IllegalArgumentException( err );
}
_classes = new Vector( 1 );
this.source = new JSourceCode();
_signature = new JMethodSignature( name, returnType );
this.jdc = _signature.getJDocComment();
jdc.appendComment( "Method " + name + "." );
//-- create comment
if ( returnType != null )
{
if ( returnDoc != null && returnDoc.length() > 0 )
{
jdc.addDescriptor( JDocDescriptor.createReturnDesc( returnDoc ) );
}
else
{
jdc.addDescriptor( JDocDescriptor.createReturnDesc( returnType.getLocalName() ) );
}
}
}
/**
* Adds the given Exception to this Method's throws clause.
*
* @param exp the JClass representing the Exception
**/
public void addException( JClass exp )
{
_signature.addException( exp );
} //-- addException
/**
* Adds the given parameter to this JMethod's list of parameters.
*
* @param parameter the parameter to add to the this Methods
* list of parameters.
* @throws java.lang.IllegalArgumentException when a parameter already
* exists for this Method with the same name as the new parameter
**/
public void addParameter( JParameter parameter )
throws IllegalArgumentException
{
_signature.addParameter( parameter );
} //-- addParameter
/**
* Returns the JDocComment describing this member.
* @return the JDocComment describing this member.
**/
public JDocComment getJDocComment()
{
return this.jdc;
} //-- getJDocComment
/**
* Returns the class in which this JMember has been declared
* @return the class in which this JMember has been declared
**
public JClass getDeclaringClass() {
return _declaringClass;
} //-- getDeclaringClass
*/
/**
* Returns the exceptions that this JMember throws.
*
* @return the exceptions that this JMember throws.
**/
public JClass[] getExceptions()
{
return _signature.getExceptions();
} //-- getExceptions
/**
* Returns the modifiers for this JMember.
*
* @return the modifiers for this JMember.
**/
public JModifiers getModifiers()
{
return _signature.getModifiers();
} //-- getModifiers
/**
* Returns the name of this JMember.
*
* @return the name of this JMember.
**/
public String getName()
{
return _signature.getName();
} //-- getName
/**
* Returns the JParameter at the given index.
*
* @param index the index of the JParameter to return.
* @return the JParameter at the given index.
**/
public JParameter getParameter( int index )
{
return _signature.getParameter( index );
} //-- getParameter
/**
* Returns the set of JParameters for this JMethod.
*
* Note: the array is a copy, the params in the array
* are the actual references.
*
* @return the set of JParameters for this JMethod
**/
public JParameter[] getParameters()
{
return _signature.getParameters();
} //-- getParameters
/**
* Returns the JType that represents the return type of the method.
*
* @return the JType that represents the return type of the method.
**/
public JType getReturnType()
{
return _signature.getReturnType();
} //-- getReturnType
/**
* Returns the JMethodSignature for this JMethod.
*
* @return the JMethodSignature for this JMethod.
**/
public JMethodSignature getSignature()
{
return _signature;
} //-- getSignature
/**
* Returns the JSourceCode for the method body.
*
* @return the JSourceCode for the method body.
**/
public JSourceCode getSourceCode()
{
return this.source;
} //-- getSourceCode
/**
* Sets the comment describing this member. The comment
* will be printed when this member is printed with the
* Class Printer.
*
* @param comment the comment for this member
* @see #getJDocComment
**/
public void setComment( String comment )
{
jdc.setComment( comment );
} //-- setComment
/**
* Sets the JModifiers for this JMethod. This
* JMethod will use only a copy of the JModifiers.
* Note: The JModifiers will be set in the
* containing JMethodSignature. If the JMethodSignature
* is used by other methods, keep in mind that it will be
* changed.
*
* @param modifiers the JModifiers to set.
**/
public void setModifiers( JModifiers modifiers )
{
_signature.setModifiers( modifiers );
} //-- setModifiers
/**
* Sets the given string as the source code (method body)
* for this JMethod.
*
* @param source the String that represents the method body.
**/
public void setSourceCode( String source )
{
this.source = new JSourceCode( source );
} //-- setSource
/**
* Sets the given JSourceCode as the source code (method body)
* for this JMethod.
*
* @param source the JSourceCode that represents the method body.
**/
public void setSourceCode( JSourceCode source )
{
this.source = source;
} //-- setSource;
/**
* Prints this JMethod to the given JSourceWriter.
*
* @param jsw the JSourceWriter to print to.
**/
public void print( JSourceWriter jsw )
{
//------------/
//- Java Doc -/
//------------/
jdc.print( jsw );
//--------------------/
// - Annotations -/
//--------------------/
JAnnotations annotations = getAnnotations();
if ( annotations != null ) annotations.print( jsw );
//--------------------/
//- Method Signature -/
//--------------------/
_signature.print( jsw, false );
if ( _signature.getModifiers().isAbstract() )
{
jsw.writeln( ";" );
}
else
{
jsw.writeln();
jsw.writeln( "{" );
source.print( jsw );
jsw.write( "} //-- " );
jsw.writeln( toString() );
}
} //-- print
/**
* Returns the String representation of this JMethod,
* which is the method prototype.
* @return the String representation of this JMethod, which
* is simply the method prototype
**/
public String toString()
{
return _signature.toString();
} //-- toString
//---------------------/
//- PROTECTED METHODS -/
//---------------------/
/**
* Adds the given JClass to the set of classes that
* contain this method.
*
* @param jClass the JClass to add as one of
* the JClasses that contain this method.
**/
protected void addDeclaringClass( JClass jClass )
{
_classes.addElement( jClass );
} //-- addDeclaringClass
/**
* Removes the given JClass from the set of classes that
* contain this method.
*
* @param jClass the JClass to add as one of
* the JClasses that contain this method.
**/
protected void removeDeclaringClass( JClass jClass )
{
_classes.removeElement( jClass );
} //-- removeDeclaringClass
protected String[] getParameterClassNames()
{
return _signature.getParameterClassNames();
} //-- getParameterClassNames
/**
* @return the annotations
*/
public JAnnotations getAnnotations()
{
return annotations;
}
/**
* @param annotation the annotation to append
*/
public void appendAnnotation( String annotation )
{
if ( annotations == null )
{
annotations = new JAnnotations();
}
annotations.appendAnnotation( annotation );
}
/**
* @param annotations the annotations to set
*/
public void setAnnotations( JAnnotations annotations )
{
this.annotations = annotations;
}
} //-- JMember
././@LongLink 0000000 0000000 0000000 00000000175 00000000000 011570 L ustar root root modello-1.1/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/javasource/JSourceWriter.java modello-1.1/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/javas0000644 0001750 0001750 00000036540 11230437043 032676 0 ustar mkoch mkoch /**
* Redistribution and use of this software and associated documentation
* ("Software"), with or without modification, are permitted provided
* that the following conditions are met:
*
* 1. Redistributions of source code must retain copyright
* statements and notices. Redistributions must also contain a
* copy of this document.
*
* 2. Redistributions in binary form must reproduce the
* above copyright notice, this list of conditions and the
* following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* 3. The name "Exolab" must not be used to endorse or promote
* products derived from this Software without prior written
* permission of Intalio, Inc. For written permission,
* please contact info@codehaus.org.
*
* 4. Products derived from this Software may not be called "Exolab"
* nor may "Exolab" appear in their names without prior written
* permission of Intalio, Inc. Exolab is a registered
* trademark of Intalio, Inc.
*
* 5. Due credit should be given to the Exolab Project
* (http://www.codehaus.org/).
*
* THIS SOFTWARE IS PROVIDED BY INTALIO, INC. AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT
* NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
* INTALIO, INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Copyright 1999 (C) Intalio, Inc. All Rights Reserved.
*
* $Id: JSourceWriter.java 1292 2009-07-18 21:26:59Z hboutemy $
*/
package org.codehaus.modello.plugin.java.javasource;
/*
* Copyright (c) 2004, Codehaus.org
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is furnished to do
* so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
import java.io.Writer;
/**
* The writer used by the modello classes
* @author Keith Visco
* @version $Revision: 1292 $ $Date: 2009-07-18 23:26:59 +0200 (Sa, 18. Jul 2009) $
**/
public class JSourceWriter extends Writer
{
/**
* The default character to use for indentation
**/
public static final char DEFAULT_CHAR = ' ';
/**
* The default indentation size
**/
public static final short DEFAULT_SIZE = 4;
/**
* The line separator to use for the writeln methods
**/
private String lineSeparator = System.getProperty( "line.separator" );
/**
* Flag for indicating whether we need to add
* the whitespace to beginning of next write
* call
**/
private boolean addIndentation = true;
/**
* A flag indicating whether this JSourceWriter should perform
* autoflush at the end of a new line
**/
private boolean autoflush = false;
/**
* The tab (indentation) size
**/
private short tabSize = DEFAULT_SIZE;
/**
* The tab representation
**/
private char[] tab;
/**
* The character to use for indentation
**/
private char tabChar = DEFAULT_CHAR;
/**
* The current tab level
**/
private short tabLevel = 0;
/**
* The writer to send all output to
**/
private Writer out = null;
/**
* Creates a new JSourceWriter
* @param out the Writer to write the actual output to
**/
public JSourceWriter( Writer out )
{
this( out, DEFAULT_SIZE, DEFAULT_CHAR, false );
} //-- JSourceWriter
/**
* Creates a new JSourceWriter
* @param out the Writer to write the actual output to
* @param autoflush a boolean indicating whether or not to
* perform automatic flush at the end of a line
**/
public JSourceWriter( Writer out, boolean autoflush )
{
this( out, DEFAULT_SIZE, DEFAULT_CHAR, autoflush );
} //-- JSourceWriter
/**
* Creates a new JSourceWriter
* @param out the Writer to write the actual output to
* @param tabSize the size of each indentation
* @param autoflush a boolean indicating whether or not to
* perform automatic flush at the end of a line
**/
public JSourceWriter
( Writer out, short tabSize, boolean autoflush )
{
this( out, tabSize, DEFAULT_CHAR, autoflush );
} //-- JSourceWriter
/**
* Creates a new JSourceWriter
* @param out the Writer to write the actual output to
* @param tabSize the size of each indentation
* @param tabChar the character to use for indentation
* @param autoflush a boolean indicating whether or not to
* perform automatic flush at the end of a line
**/
public JSourceWriter
( Writer out, short tabSize, char tabChar, boolean autoflush )
{
this.out = out;
this.autoflush = autoflush;
this.tabChar = tabChar;
this.tabSize = tabSize;
createTab();
} //-- JSourceWriter
/**
* Returns the line separator being used by this JSourceWriter
* @return the line separator being used by this JSourceWriter
**/
public String getLineSeparator()
{
return lineSeparator;
} //-- getLineSeparator
/**
* Increases the indentation level by 1
**/
public void indent()
{
++tabLevel;
} //-- increaseIndent
/**
* Checks to see if the cursor is positioned on a new line
* @return true if the cursor is at the start of a new line, otherwise false
**/
public boolean isNewline()
{
//-- if we need to add indentation, we are on a new line
return addIndentation;
} //-- isNewline
/**
* Sets the line separator to use at the end of each line
* @param lineSeparator the String to use as a line
* separator.
*
* Typically a line separator will be one of the following:
*
* "\r\n" for MS Windows
* "\n" for UNIX
* "\r" for Macintosh
**/
public void setLineSeparator( String lineSeparator )
{
this.lineSeparator = lineSeparator;
} //-- setLineSeparator
/**
* Decreases the indentation level by 1
**/
public void unindent()
{
if ( tabLevel > 0 ) --tabLevel;
} //-- decreaseIndent
//----------------------------/
//- Additional write methods -/
//----------------------------/
public void write( float f )
{
write( String.valueOf( f ) );
} //-- write(float)
public void write( long l )
{
write( String.valueOf( l ) );
} //-- write(long)
public void write( double d )
{
write( String.valueOf( d ) );
} //-- write(double)
public void write( Object obj )
{
write( obj.toString() );
} //-- write(Object)
public void write( boolean b )
{
write( String.valueOf( b ) );
} //-- write(boolean)
//- writeln() methods
public void writeln()
{
synchronized ( lock )
{
linefeed();
addIndentation = true;
}
} //-- writeln
public void writeln( float f )
{
synchronized ( lock )
{
ensureIndent();
try
{
out.write( String.valueOf( f ) );
}
catch ( java.io.IOException ioe )
{
}
;
linefeed();
addIndentation = true;
}
} //-- writeln(float)
public void writeln( long l )
{
synchronized ( lock )
{
ensureIndent();
try
{
out.write( String.valueOf( l ) );
}
catch ( java.io.IOException ioe )
{
}
;
linefeed();
addIndentation = true;
}
} //-- writeln(long)
public void writeln( int i )
{
synchronized ( lock )
{
ensureIndent();
try
{
out.write( String.valueOf( i ) );
}
catch ( java.io.IOException ioe )
{
}
;
linefeed();
addIndentation = true;
}
} //-- writeln(int)
public void writeln( double d )
{
synchronized ( lock )
{
ensureIndent();
try
{
out.write( String.valueOf( d ) );
}
catch ( java.io.IOException ioe )
{
}
;
linefeed();
addIndentation = true;
}
} //-- writeln(double)
public void writeln( Object obj )
{
synchronized ( lock )
{
ensureIndent();
try
{
out.write( obj.toString() );
}
catch ( java.io.IOException ioe )
{
}
;
linefeed();
addIndentation = true;
}
} //-- writeln(Object)
public void writeln( String string )
{
synchronized ( lock )
{
if ( string.length() > 0 )
{
ensureIndent();
try
{
out.write( string );
}
catch ( java.io.IOException ioe )
{
}
}
linefeed();
addIndentation = true;
}
} //-- writeln(String)
public void writeln( char[] chars )
{
synchronized ( lock )
{
ensureIndent();
try
{
out.write( chars );
}
catch ( java.io.IOException ioe )
{
}
;
linefeed();
addIndentation = true;
}
} //-- writeln(char[])
public void writeln( boolean b )
{
synchronized ( lock )
{
ensureIndent();
try
{
out.write( String.valueOf( b ) );
}
catch ( java.io.IOException ioe )
{
}
;
linefeed();
addIndentation = true;
}
} //-- writeln(boolean)
public void writeln( char c )
{
synchronized ( lock )
{
ensureIndent();
try
{
out.write( c );
}
catch ( java.io.IOException ioe )
{
}
;
linefeed();
addIndentation = true;
}
} //-- writeln(char)
//-----------------------/
//- Methods from Writer -/
//-----------------------/
public void close()
{
try
{
out.close();
}
catch ( java.io.IOException ioe )
{
}
;
} //-- close
public void flush()
{
try
{
out.flush();
}
catch ( java.io.IOException ioe )
{
}
;
} //-- flush
public void write( String s, int off, int len )
{
synchronized ( lock )
{
ensureIndent();
try
{
out.write( s, off, len );
}
catch ( java.io.IOException ioe )
{
}
;
if ( autoflush ) flush();
}
} //-- write
public void write( String s )
{
synchronized ( lock )
{
ensureIndent();
try
{
out.write( s );
}
catch ( java.io.IOException ioe )
{
}
;
if ( autoflush ) flush();
}
} //-- write
public void write( char[] buf )
{
synchronized ( lock )
{
ensureIndent();
try
{
out.write( buf );
}
catch ( java.io.IOException ioe )
{
}
;
if ( autoflush ) flush();
}
} //-- write
public void write( int c )
{
synchronized ( lock )
{
ensureIndent();
try
{
out.write( c );
}
catch ( java.io.IOException ioe )
{
}
;
if ( autoflush ) flush();
}
} //-- write
public void write( char[] buf, int off, int len )
{
synchronized ( lock )
{
ensureIndent();
try
{
out.write( buf, off, len );
}
catch ( java.io.IOException ioe )
{
}
;
if ( autoflush ) flush();
}
} //-- write
//---------------------/
//- Protected Methods -/
//---------------------/
protected short getIndentLevel()
{
return tabLevel;
}
/**
* Returns the current indent size (getIndentLevel()*tabSize);
* @return the current indent size
**/
protected short getIndentSize()
{
return (short) ( tabLevel * tabSize );
} //-- getIndentSize
protected char getIndentChar()
{
return tabChar;
}
protected void writeIndent()
{
try
{
for ( int i = 0; i < tabLevel; i++ ) out.write( tab );
}
catch ( java.io.IOException ioe )
{
}
;
} //-- writeIndent
//-------------------/
//- Private Methods -/
//-------------------/
private void ensureIndent()
{
if ( addIndentation )
{
writeIndent();
addIndentation = false;
}
} //-- ensureIndent
/**
* writes the line separator character to the writer
**/
private void linefeed()
{
try
{
out.write( lineSeparator );
}
catch ( java.io.IOException ioe )
{
}
;
} //-- linefeed
/**
* Creates the tab from the tabSize and the tabChar
**/
private void createTab()
{
tab = new char[tabSize];
for ( int i = 0; i < tabSize; i++ )
{
tab[i] = tabChar;
}
} //-- createTab
} //-- JSourceWriter
././@LongLink 0000000 0000000 0000000 00000000177 00000000000 011572 L ustar root root modello-1.1/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/javasource/JCollectionType.java modello-1.1/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/javas0000644 0001750 0001750 00000006303 11123536732 032676 0 ustar mkoch mkoch /*
* Copyright 2006 Werner Guttmann
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.codehaus.modello.plugin.java.javasource;
/**
* JType sub-class for collections.
*
* @author Werner Guttman
* @version $Revision: 1041 $ $Date: 2008-12-21 23:06:18 +0100 (So, 21. Dez 2008) $
* @since 1.0.4
*/
public final class JCollectionType
extends JComponentizedType
{
// --------------------------------------------------------------------------
/** Name of the actual collection instance to be used, e.g. java.util.ArrayList. */
private String _instanceName;
// --------------------------------------------------------------------------
/**
* Creates an instance of a collection type, of type 'collectionName'.
*
* @param typeName Name of the collection type interface.
* @param componentType Component type.
* @param useJava50 True if Java 5.0 should be used.
*/
public JCollectionType( final String typeName, final JType componentType, final boolean useJava50 )
{
super( typeName, componentType, useJava50 );
}
/**
* Creates an instance of a collection type, of type 'collectionName'.
*
* @param typeName Name of the collection type interface.
* @param instanceName Name of the actual collection type instance.
* @param componentType Component type.
* @param useJava50 True if Java 5.0 should be used.
*/
public JCollectionType( final String typeName, final String instanceName, final JType componentType,
final boolean useJava50 )
{
super( typeName, componentType, useJava50 );
_instanceName = instanceName;
}
// --------------------------------------------------------------------------
/**
* Returns the instance name of this collection type.
*
* @return The instance name of this collection type.
*/
public String getInstanceName()
{
if ( _instanceName != null )
{
if ( isUseJava50() )
{
return _instanceName + "<" + getComponentType().toString() + ">";
}
return _instanceName + "/*<" + getComponentType().toString() + ">*/";
}
return toString();
}
/**
* {@inheritDoc}
* Returns the String representation of this JType.
*/
public String toString()
{
if ( isUseJava50() )
{
return getName() + "<" + getComponentType().toString() + ">";
}
return getName() + "/*<" + getComponentType().toString() + ">*/";
}
// --------------------------------------------------------------------------
}
././@LongLink 0000000 0000000 0000000 00000000176 00000000000 011571 L ustar root root modello-1.1/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/javasource/JDocDescriptor.java modello-1.1/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/javas0000644 0001750 0001750 00000026736 10664275111 032712 0 ustar mkoch mkoch /**
* Redistribution and use of this software and associated documentation
* ("Software"), with or without modification, are permitted provided
* that the following conditions are met:
*
* 1. Redistributions of source code must retain copyright
* statements and notices. Redistributions must also contain a
* copy of this document.
*
* 2. Redistributions in binary form must reproduce the
* above copyright notice, this list of conditions and the
* following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* 3. The name "Exolab" must not be used to endorse or promote
* products derived from this Software without prior written
* permission of Intalio, Inc. For written permission,
* please contact info@codehaus.org.
*
* 4. Products derived from this Software may not be called "Exolab"
* nor may "Exolab" appear in their names without prior written
* permission of Intalio, Inc. Exolab is a registered
* trademark of Intalio, Inc.
*
* 5. Due credit should be given to the Exolab Project
* (http://www.codehaus.org/).
*
* THIS SOFTWARE IS PROVIDED BY INTALIO, INC. AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT
* NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
* INTALIO, INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Copyright 1999 (C) Intalio, Inc. All Rights Reserved.
*
* $Id: JDocDescriptor.java 858 2007-08-26 13:04:09Z hboutemy $
*/
package org.codehaus.modello.plugin.java.javasource;
/*
* Copyright (c) 2004, Codehaus.org
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is furnished to do
* so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
/**
* A descriptor for a JavaDoc comment
* @author Keith Visco
* @version $Revision: 858 $ $Date: 2007-08-26 15:04:09 +0200 (So, 26. Aug 2007) $
**/
public class JDocDescriptor
{
/**
* The default version string
**/
//-- separated using "+" so that CVS doesn't expand
public static final String DEFAULT_VERSION =
"$" + "Revision" + "$ $" + "Date" + "$";
//-- These are listed in order of how they should
//-- appear in a JavaDoc list, so the numbers
//-- are important...see #compareTo
/**
* The param descriptor (param)
**/
public static final short PARAM = 0;
/**
* The exception descriptor (exception)
**/
public static final short EXCEPTION = 1;
/**
* The return descriptor (return)
**/
public static final short RETURN = 2;
/**
* The author descriptor
**/
public static final short AUTHOR = 3;
/**
* the version descriptor (version)
**/
public static final short VERSION = 4;
/**
* The reference descriptor (see)
**/
public static final short REFERENCE = 5;
private String description = null;
private String name = null;
private short type = -1;
/**
* Creates a new JDocDescriptor
**/
private JDocDescriptor( short type )
{
this.type = type;
} //-- JDocDescriptor
/**
* Creates a new JDocDescriptor
* @param name the name string for this descriptor
* @param desc the description string for this descriptor
**/
private JDocDescriptor( short type, String name, String desc )
{
this.type = type;
this.name = name;
this.description = desc;
} //-- JDocDescriptor
/**
* Compares the type of this JDocDescriptor with the given descriptor.
* Enables sorting of descriptors.
* @return 0 if the two descriptor types are equal, 1 if the type of
* this descriptor is greater than the given descriptor, or -1 if the
* type of this descriptor is less than the given descriptor
**/
protected short compareTo( JDocDescriptor jdd )
{
short jddType = jdd.getType();
if ( jddType == this.type ) return 0;
// The ordering is as follows
// #param
// #exception
// #author
// #version
// #see (reference)
//
return (short) ( ( jddType < this.type ) ? 1 : -1 );
} //-- compareTo
/**
* Creates a new author descriptor
* @return the new JDocDescriptor
**/
public static JDocDescriptor createAuthorDesc()
{
return new JDocDescriptor( AUTHOR );
} //-- createAuthorDesc
/**
* Creates a new author descriptor
* @param name the author name string
* @return the new JDocDescriptor
**/
public static JDocDescriptor createAuthorDesc( String name )
{
return new JDocDescriptor( AUTHOR, name, null );
} //-- createAuthorDesc
/**
* Creates a new exception descriptor
* @return the new JDocDescriptor
**/
public static JDocDescriptor createExceptionDesc()
{
return new JDocDescriptor( EXCEPTION );
} //-- createExceptionDesc
/**
* Creates a new exception descriptor
* @param name the exception name
* @param desc the description of when the exception is called
* @return the new JDocDescriptor
**/
public static JDocDescriptor createExceptionDesc
( String name, String desc )
{
return new JDocDescriptor( EXCEPTION, name, desc );
} //-- createExceptionDesc
/**
* Creates a new param descriptor
* @return the new JDocDescriptor
**/
public static JDocDescriptor createParamDesc()
{
return new JDocDescriptor( PARAM );
} //-- createParamDesc
/**
* Creates a new param descriptor
* @param name the param name
* @param desc the param description string
* @return the new JDocDescriptor
**/
public static JDocDescriptor createParamDesc( String name, String desc )
{
return new JDocDescriptor( PARAM, name, desc );
} //-- createParamDesc
/**
* Creates a new reference descriptor
* @return the new JDocDescriptor
**/
public static JDocDescriptor createReferenceDesc()
{
return new JDocDescriptor( REFERENCE );
} //-- createReferenceDesc
/**
* Creates a new reference descriptor
* @param name the reference name string
* @return the new JDocDescriptor
**/
public static JDocDescriptor createReferenceDesc( String name )
{
return new JDocDescriptor( REFERENCE, name, null );
} //-- createReferenceDesc
/**
* Creates a new return descriptor
* @return the new JDocDescriptor
**/
public static JDocDescriptor createReturnDesc()
{
return new JDocDescriptor( RETURN );
} //-- createReferenceDesc
/**
* Creates a new return descriptor
* @param desc the return description
* @return the new JDocDescriptor
**/
public static JDocDescriptor createReturnDesc( String desc )
{
return new JDocDescriptor( RETURN, null, desc );
} //-- createReturnDesc
/**
* Creates a new version descriptor
* @return the new JDocDescriptor
**/
public static JDocDescriptor createVersionDesc()
{
return new JDocDescriptor( VERSION );
} //-- createVersionDesc
/**
* Creates a new version descriptor
* @param version the version string
* @return the new JDocDescriptor
**/
public static JDocDescriptor createVersionDesc( String version )
{
return new JDocDescriptor( VERSION, null, version );
} //-- createVersionDesc
/**
* Returns the description String for this descriptor
* @return the description string for this descriptor
**/
public String getDescription()
{
return description;
} //-- getDescription
/**
* Returns the name of the object being described. This
* is valid for the following fields:
*
* This method is implemented by subclasses and * should only accept the proper fields for the * subclass otherwise an IllegalArgumentException * will be thrown. For example a JInterface will * only accept static fields. *
* @param jField, the JField to add * @exception java.lang.IllegalArgumentException when the given * JField has a name of an existing JField */ public void addField( JField jField ) throws IllegalArgumentException { if ( jField == null ) { throw new IllegalArgumentException( "argument 'jField' cannot be null" ); } String name = jField.getName(); //-- check for duplicate field name if ( ( fields != null ) && ( fields.get( name ) != null ) ) { String err = "duplicate name found: " + name; throw new IllegalArgumentException( err ); } //-- check for proper modifiers JModifiers modifiers = jField.getModifiers(); if ( !modifiers.isStatic() ) { throw new IllegalArgumentException( "Fields added to a JInterface must be static." ); } if ( modifiers.isPrivate() ) { throw new IllegalArgumentException( "Fields added to a JInterface must not be private." ); } //-- only initialize fields if we need it, many interfaces //-- don't contain any fields, no need to waste space if ( fields == null ) { fields = new JNamedMap( 3 ); } fields.put( name, jField ); } /** * Adds the given JMember to this JStructure. *
* This method is implemented by subclasses and * should only accept the proper types for the * subclass otherwise an IllegalArgumentException * will be thrown. *
* @param jMember the JMember to add to this JStructure.
* @throws java.lang.IllegalArgumentException when the given
* JMember has the same name of an existing JField
* or JMethod respectively.
*/
public void addMember( JMember jMember )
throws IllegalArgumentException
{
if ( jMember == null )
{
throw new IllegalArgumentException( "argument 'jMember' may not be null." );
}
if ( jMember instanceof JField )
{
addField( (JField) jMember );
}
else
{
throw new IllegalArgumentException( "invalid member for JInterface: " +
jMember.toString() );
}
} //-- addMember
/**
* Adds the given JMethodSignature to this JClass
*
* @param jMethodSig the JMethodSignature to add.
* @throws java.lang.IllegalArgumentException when the given
* JMethodSignature conflicts with an existing
* method signature.
*/
public void addMethod( JMethodSignature jMethodSig )
throws IllegalArgumentException
{
if ( jMethodSig == null )
{
String err = "The JMethodSignature cannot be null.";
throw new IllegalArgumentException( err );
}
//-- check method name and signatures *add later*
//-- keep method list sorted for esthetics when printing
//-- START SORT :-)
boolean added = false;
// short modifierVal = 0;
JModifiers modifiers = jMethodSig.getModifiers();
for ( int i = 0; i < methods.size(); i++ )
{
JMethodSignature tmp = (JMethodSignature) methods.elementAt( i );
//-- first compare modifiers
if ( tmp.getModifiers().isProtected() )
{
if ( !modifiers.isProtected() )
{
methods.insertElementAt( jMethodSig, i );
added = true;
break;
}
}
//-- compare names
if ( jMethodSig.getName().compareTo( tmp.getName() ) < 0 )
{
methods.insertElementAt( jMethodSig, i );
added = true;
break;
}
}
//-- END SORT
if ( !added ) methods.addElement( jMethodSig );
//-- check return type to make sure it's included in the
//-- import list
JType jType = jMethodSig.getReturnType();
if ( jType != null )
{
while ( jType.isArray() )
jType = jType.getComponentType();
if ( !jType.isPrimitive() )
addImport( jType.getName() );
}
//-- check exceptions
JClass[] exceptions = jMethodSig.getExceptions();
for ( int i = 0; i < exceptions.length; i++ )
{
addImport( exceptions[i].getName() );
}
} //-- addMethod
/**
* Returns the field with the given name, or null if no field
* was found with the given name.
*
* @param name the name of the field to return.
* @return the field with the given name, or null if no field
* was found with the given name.
*/
public JField getField( String name )
{
if ( fields == null ) return null;
return (JField) fields.get( name );
} //-- getField
/**
* Returns an array of all the JFields of this JStructure
*
* @return an array of all the JFields of this JStructure
*/
public JField[] getFields()
{
if ( fields == null )
{
return new JField[0];
}
int size = fields.size();
JField[] farray = new JField[size];
for ( int i = 0; i < size; i++ )
{
farray[i] = (JField) fields.get( i );
}
return farray;
} //-- getFields
/**
* Returns an array of all the JMethodSignatures of this JInterface.
*
* @return an array of all the JMethodSignatures of this JInterface.
**/
public JMethodSignature[] getMethods()
{
JMethodSignature[] marray = new JMethodSignature[methods.size()];
methods.copyInto( marray );
return marray;
} //-- getMethods
/**
* Returns the JMethodSignature with the given name,
* and occuring at or after the given starting index.
*
* @param name the name of the JMethodSignature to return.
* @param startIndex the starting index to begin searching
* from.
* @return the JMethodSignature, or null if not found.
**/
public JMethodSignature getMethod( String name, int startIndex )
{
for ( int i = startIndex; i < methods.size(); i++ )
{
JMethodSignature jMethod = (JMethodSignature) methods.elementAt( i );
if ( jMethod.getName().equals( name ) ) return jMethod;
}
return null;
} //-- getMethod
/**
* Returns the JMethodSignature at the given index.
*
* @param index the index of the JMethodSignature to return.
* @return the JMethodSignature at the given index.
**/
public JMethodSignature getMethod( int index )
{
return (JMethodSignature) methods.elementAt( index );
} //-- getMethod
/**
* Prints the source code for this JInterface to the given JSourceWriter
*
* @param jsw the JSourceWriter to print to. [May not be null]
*/
public void print( JSourceWriter jsw )
{
print( jsw, false );
}
/**
* Prints the source code for this JInterface to the given JSourceWriter
*
* @param jsw the JSourceWriter to print to. [May not be null]
*/
public void print( JSourceWriter jsw, boolean classOnly )
{
if ( jsw == null )
{
throw new IllegalArgumentException( "argument 'jsw' should not be null." );
}
StringBuffer buffer = new StringBuffer();
if ( !classOnly )
{
printHeader( jsw );
printPackageDeclaration( jsw );
printImportDeclarations( jsw );
}
//------------/
//- Java Doc -/
//------------/
getJDocComment().print( jsw );
JAnnotations annotations = getAnnotations();
if ( annotations != null ) annotations.print( jsw );
//-- print class information
//-- we need to add some JavaDoc API adding comments
buffer.setLength( 0 );
JModifiers modifiers = getModifiers();
if ( modifiers.isPrivate() )
{
buffer.append( "private " );
}
else if ( modifiers.isPublic() )
{
buffer.append( "public " );
}
if ( modifiers.isAbstract() )
{
buffer.append( "abstract " );
}
buffer.append( "interface " );
buffer.append( getLocalName() );
jsw.writeln( buffer.toString() );
buffer.setLength( 0 );
jsw.indent();
if ( getInterfaceCount() > 0 )
{
Enumeration e = getInterfaces();
buffer.append( "extends " );
while ( e.hasMoreElements() )
{
buffer.append( e.nextElement() );
if ( e.hasMoreElements() ) buffer.append( ", " );
}
jsw.writeln( buffer.toString() );
buffer.setLength( 0 );
}
jsw.unindent();
jsw.writeln( '{' );
jsw.indent();
//-- declare static members
if ( fields != null )
{
if ( fields.size() > 0 )
{
jsw.writeln();
jsw.writeln( " //--------------------------/" );
jsw.writeln( " //- Class/Member Variables -/" );
jsw.writeln( "//--------------------------/" );
jsw.writeln();
}
for ( int i = 0; i < fields.size(); i++ )
{
JField jField = (JField) fields.get( i );
//-- print Java comment
JDocComment comment = jField.getComment();
if ( comment != null ) comment.print( jsw );
// -- print member
jsw.write( jField.getModifiers().toString() );
jsw.write( ' ' );
JType type = jField.getType();
String typeName = type.toString();
//-- for esthetics use short name in some cases
if ( typeName.equals( toString() ) )
{
typeName = type.getLocalName();
}
jsw.write( typeName );
jsw.write( ' ' );
jsw.write( jField.getName() );
String init = jField.getInitString();
if ( init != null )
{
jsw.write( " = " );
jsw.write( init );
}
jsw.writeln( ';' );
jsw.writeln();
}
}
//-- print method signatures
if ( methods.size() > 0 )
{
jsw.writeln();
jsw.writeln( " //-----------/" );
jsw.writeln( " //- Methods -/" );
jsw.writeln( "//-----------/" );
jsw.writeln();
}
for ( int i = 0; i < methods.size(); i++ )
{
JMethodSignature signature = (JMethodSignature) methods.elementAt( i );
signature.print( jsw );
jsw.writeln( ';' );
}
for ( Iterator iterator = sourceCodeEntries.iterator(); iterator.hasNext(); )
{
jsw.writeln( (String) iterator.next() );
}
jsw.unindent();
jsw.writeln( '}' );
jsw.flush();
jsw.close();
} //-- printSource
private List sourceCodeEntries = new ArrayList();
public void addSourceCode( String sourceCode )
{
sourceCodeEntries.add( sourceCode );
}
/**
* Test drive method...to be removed or commented out
**
public static void main(String[] args) {
JInterface jInterface = new JInterface("Test");
//-- add an import
jInterface.addImport("java.util.Vector");
JClass jString = new JClass("String");
//-- add an interface
jInterface.addInterface("java.io.Serializable");
//-- add a static field
JField jField = new JField(new JClass("java.lang.String"), "TEST");
jField.setInitString("\"Test\"");
jField.getModifiers().setStatic(true);
jField.getModifiers().makePublic();
jInterface.addField(jField);
//-- add a method signature
JMethodSignature jMethodSig = new JMethodSignature("getName", jString);
jInterface.addMethod(jMethodSig);
jInterface.print();
} //-- main
/* */
} //-- JInterface
././@LongLink 0000000 0000000 0000000 00000000174 00000000000 011567 L ustar root root modello-1.1/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/javasource/JConstructor.java modello-1.1/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/javas0000644 0001750 0001750 00000021157 11231735057 032703 0 ustar mkoch mkoch /**
* Redistribution and use of this software and associated documentation
* ("Software"), with or without modification, are permitted provided
* that the following conditions are met:
*
* 1. Redistributions of source code must retain copyright
* statements and notices. Redistributions must also contain a
* copy of this document.
*
* 2. Redistributions in binary form must reproduce the
* above copyright notice, this list of conditions and the
* following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* 3. The name "Exolab" must not be used to endorse or promote
* products derived from this Software without prior written
* permission of Intalio, Inc. For written permission,
* please contact info@codehaus.org.
*
* 4. Products derived from this Software may not be called "Exolab"
* nor may "Exolab" appear in their names without prior written
* permission of Intalio, Inc. Exolab is a registered
* trademark of Intalio, Inc.
*
* 5. Due credit should be given to the Exolab Project
* (http://www.codehaus.org/).
*
* THIS SOFTWARE IS PROVIDED BY INTALIO, INC. AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT
* NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
* INTALIO, INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Copyright 1999 (C) Intalio, Inc. All Rights Reserved.
*
* $Id: JConstructor.java 1297 2009-07-23 01:17:35Z hboutemy $
*/
package org.codehaus.modello.plugin.java.javasource;
/*
* Copyright (c) 2004, Codehaus.org
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is furnished to do
* so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
/**
* A class for handling source code for a constructor of a JClass
* @author Keith Visco
* @version $Revision: 1297 $ $Date: 2009-07-23 03:17:35 +0200 (Do, 23. Jul 2009) $
**/
public class JConstructor
{
/**
* The set of modifiers for this JMethod
**/
private JModifiers modifiers = null;
/**
* List of parameters for this Constructor
**/
private JNamedMap params = null;
/**
* The Class in this JMember has been declared
**/
private JClass declaringClass = null;
private JSourceCode sourceCode = null;
private JAnnotations annotations = null;
/**
* Creates a new method with the given name and returnType.
* For "void" return types, simply pass in null as the returnType
**/
public JConstructor( JClass declaringClass )
{
this.declaringClass = declaringClass;
this.modifiers = new JModifiers();
this.params = new JNamedMap();
this.sourceCode = new JSourceCode();
}
/**
* Adds the given parameter to this Methods list of parameters
* @param parameter the parameter to add to the this Methods
* list of parameters.
* @exception java.lang.IllegalArgumentException when a parameter already
* exists for this Method with the same name as the new parameter
**/
public void addParameter( JParameter parameter )
throws IllegalArgumentException
{
if ( parameter == null ) return;
//-- check current params
if ( params.get( parameter.getName() ) != null )
{
StringBuffer err = new StringBuffer();
err.append( "A parameter already exists for the constructor, " );
err.append( this.declaringClass.getName() );
err.append( ", with the name: " );
err.append( parameter.getName() );
throw new IllegalArgumentException( err.toString() );
}
params.put( parameter.getName(), parameter );
} //-- addParameter
/**
* Returns the class in which this JMember has been declared
* @return the class in which this JMember has been declared
**/
public JClass getDeclaringClass()
{
return this.declaringClass;
} //-- getDeclaringClass
/**
* Returns the modifiers for this JConstructor
* @return the modifiers for this JConstructor
**/
public JModifiers getModifiers()
{
return this.modifiers;
} //-- getModifiers
/**
* Returns an array of JParameters consisting of the parameters
* of this Method in declared order
* @return a JParameter array consisting of the parameters
* of this Method in declared order
**/
public JParameter[] getParameters()
{
JParameter[] jpArray = new JParameter[params.size()];
for ( int i = 0; i < jpArray.length; i++ )
{
jpArray[i] = (JParameter) params.get( i );
}
return jpArray;
} //-- getParameters
public JSourceCode getSourceCode()
{
return this.sourceCode;
} //-- getSourceCode
public void print( JSourceWriter jsw )
{
JAnnotations annotations = getAnnotations();
if ( annotations != null ) annotations.print( jsw );
if ( modifiers.isPrivate() )
jsw.write( "private" );
else if ( modifiers.isProtected() )
jsw.write( "protected" );
else
jsw.write( "public" );
jsw.write( ' ' );
jsw.write( declaringClass.getLocalName() );
jsw.write( '(' );
//-- print parameters
for ( int i = 0; i < params.size(); i++ )
{
if ( i > 0 ) jsw.write( ", " );
jsw.write( params.get( i ) );
}
jsw.writeln( ')' );
jsw.writeln( '{' );
//jsw.indent();
sourceCode.print( jsw );
//jsw.unindent();
if ( !jsw.isNewline() ) jsw.writeln();
jsw.write( "} //-- " );
jsw.writeln( toString() );
} //-- print
public void setModifiers( JModifiers modifiers )
{
this.modifiers = modifiers.copy();
this.modifiers.setFinal( false );
} //-- setModifiers
public void setSourceCode( String sourceCode )
{
this.sourceCode = new JSourceCode( sourceCode );
} //-- setSourceCode
public void setSourceCode( JSourceCode sourceCode )
{
this.sourceCode = sourceCode;
} //-- setSourceCode
public String toString()
{
StringBuffer sb = new StringBuffer();
sb.append( declaringClass.getName() );
sb.append( '(' );
//-- print parameters
for ( int i = 0; i < params.size(); i++ )
{
JParameter jp = (JParameter) params.get( i );
if ( i > 0 ) sb.append( ", " );
sb.append( jp.getType().getName() );
}
sb.append( ')' );
return sb.toString();
} //-- toString
/**
* @return the annotations
*/
public JAnnotations getAnnotations()
{
return annotations;
}
/**
* @param annotation the annotation to append
*/
public void appendAnnotation( String annotation )
{
if ( annotations == null )
{
annotations = new JAnnotations();
}
annotations.appendAnnotation( annotation );
}
/**
* @param annotations the annotations to set
*/
public void setAnnotations( JAnnotations annotations )
{
this.annotations = annotations;
}
} //-- JConstructor
././@LongLink 0000000 0000000 0000000 00000000172 00000000000 011565 L ustar root root modello-1.1/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/javasource/JArrayType.java modello-1.1/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/javas0000644 0001750 0001750 00000003411 11123536732 032673 0 ustar mkoch mkoch /*
* Copyright 2006 Werner Guttmann
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.codehaus.modello.plugin.java.javasource;
/**
* JType sub-class for Arrays.
*
* @author Werner Guttman
* @version $Revision: 1041 $ $Date: 2008-12-21 23:06:18 +0100 (So, 21. Dez 2008) $
* @since 1.0.4
*/
public final class JArrayType
extends JComponentizedType
{
// --------------------------------------------------------------------------
/**
* Creates an instance of a array type, of type 'name'.
*
* @param componentType Component type.
* @param useJava50 True if Java 5.0 should be generated.
*/
public JArrayType( final JType componentType, final boolean useJava50 )
{
super( componentType.getName(), componentType, useJava50 );
}
// --------------------------------------------------------------------------
/**
* Returns the String representation of this JType, which is simply the name of this type.
*
* @return The String representation of this JType.
*/
public String toString()
{
return getComponentType().toString() + "[]";
}
// --------------------------------------------------------------------------
}
././@LongLink 0000000 0000000 0000000 00000000201 00000000000 011556 L ustar root root modello-1.1/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/AbstractJavaModelloGenerator.java modello-1.1/modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/Abstr0000644 0001750 0001750 00000023726 11243356043 032653 0 ustar mkoch mkoch package org.codehaus.modello.plugin.java;
/*
* Copyright (c) 2004, Codehaus.org
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is furnished to do
* so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.Writer;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.Locale;
import java.util.Properties;
import org.codehaus.modello.ModelloException;
import org.codehaus.modello.ModelloParameterConstants;
import org.codehaus.modello.model.BaseElement;
import org.codehaus.modello.model.Model;
import org.codehaus.modello.model.ModelAssociation;
import org.codehaus.modello.model.ModelClass;
import org.codehaus.modello.model.ModelDefault;
import org.codehaus.modello.model.ModelField;
import org.codehaus.modello.model.ModelInterface;
import org.codehaus.modello.plugin.AbstractModelloGenerator;
import org.codehaus.modello.plugin.java.javasource.JClass;
import org.codehaus.modello.plugin.java.javasource.JComment;
import org.codehaus.modello.plugin.java.javasource.JInterface;
import org.codehaus.modello.plugin.java.javasource.JSourceWriter;
import org.codehaus.modello.plugin.java.javasource.JStructure;
import org.codehaus.modello.plugin.java.metadata.JavaClassMetadata;
import org.codehaus.modello.plugin.java.metadata.JavaFieldMetadata;
import org.codehaus.modello.plugin.java.metadata.JavaModelMetadata;
import org.codehaus.plexus.util.StringUtils;
import org.codehaus.plexus.util.WriterFactory;
/**
* AbstractJavaModelloGenerator - similar in scope to {@link AbstractModelloGenerator} but with features that
* java generators can use.
*
* @author Joakim Erdfelt
* @version $Id: AbstractJavaModelloGenerator.java 1311 2009-08-20 23:28:35Z hboutemy $
*/
public abstract class AbstractJavaModelloGenerator
extends AbstractModelloGenerator
{
protected boolean useJava5 = false;
protected void initialize( Model model, Properties parameters )
throws ModelloException
{
super.initialize( model, parameters );
useJava5 = Boolean.valueOf( getParameter( parameters,
ModelloParameterConstants.USE_JAVA5, "false" ) ).booleanValue();
}
/**
* Create a new java source file writer, with configured encoding.
*
* @param packageName the package of the source file to create
* @param className the class of the source file to create
* @return a JSourceWriter with configured encoding
* @throws IOException
*/
protected JSourceWriter newJSourceWriter( String packageName, String className )
throws IOException
{
String directory = packageName.replace( '.', File.separatorChar );
File f = new File( new File( getOutputDirectory(), directory ), className + ".java" );
if ( !f.getParentFile().exists() )
{
f.getParentFile().mkdirs();
}
OutputStream os = getBuildContext().newFileOutputStream( f );
Writer writer = ( getEncoding() == null ) ? WriterFactory.newPlatformWriter( os )
: WriterFactory.newWriter( os, getEncoding() );
return new JSourceWriter( writer );
}
private JComment getHeaderComment()
{
JComment comment = new JComment();
comment.setComment( getHeader() );
return comment;
}
protected void initHeader( JClass clazz )
{
clazz.setHeader( getHeaderComment() );
}
protected void initHeader( JInterface interfaze )
{
interfaze.setHeader( getHeaderComment() );
}
protected void suppressAllWarnings( Model objectModel, JStructure structure )
{
JavaModelMetadata javaModelMetadata = (JavaModelMetadata) objectModel.getMetadata( JavaModelMetadata.ID );
if ( useJava5 && javaModelMetadata.isSuppressAllWarnings() )
{
structure.appendAnnotation( "@SuppressWarnings( \"all\" )" );
}
}
protected void addModelImports( JClass jClass, BaseElement baseElem )
throws ModelloException
{
String basePackageName = null;
if ( baseElem != null )
{
if ( baseElem instanceof ModelInterface )
{
basePackageName =
( (ModelInterface) baseElem ).getPackageName( isPackageWithVersion(), getGeneratedVersion() );
}
else if ( baseElem instanceof ModelClass )
{
basePackageName =
( (ModelClass) baseElem ).getPackageName( isPackageWithVersion(), getGeneratedVersion() );
}
}
// import interfaces
for ( Iterator i = getModel().getInterfaces( getGeneratedVersion() ).iterator(); i.hasNext(); )
{
ModelInterface modelInterface = (ModelInterface) i.next();
String packageName = modelInterface.getPackageName( isPackageWithVersion(), getGeneratedVersion() );
if ( packageName.equals( basePackageName ) )
{
continue;
}
jClass.addImport( packageName + '.' + modelInterface.getName() );
}
// import classes
for ( Iterator i = getModel().getClasses( getGeneratedVersion() ).iterator(); i.hasNext(); )
{
ModelClass modelClass = (ModelClass) i.next();
String packageName = modelClass.getPackageName( isPackageWithVersion(), getGeneratedVersion() );
if ( packageName.equals( basePackageName ) )
{
continue;
}
JavaClassMetadata javaClassMetadata = (JavaClassMetadata) modelClass.getMetadata( JavaClassMetadata.ID );
if ( !javaClassMetadata.isEnabled() )
{
// Skip import of those classes that are not enabled for the java plugin.
continue;
}
jClass.addImport( packageName + '.' + modelClass.getName() );
}
}
protected String getPrefix( JavaFieldMetadata javaFieldMetadata )
{
return javaFieldMetadata.isBooleanGetter() ? "is" : "get";
}
protected String getDefaultValue( ModelAssociation association )
{
String value = association.getDefaultValue();
if ( useJava5 )
{
value = StringUtils.replaceOnce( StringUtils.replaceOnce( value, "/*", "" ), "*/", "" );
}
return value;
}
protected final static String DEFAULT_DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSS";
protected String getJavaDefaultValue( ModelField modelField )
throws ModelloException
{
if ( modelField.getType().equals( "String" ) )
{
return '"' + modelField.getDefaultValue() + '"';
}
else if ( modelField.getType().equals( "char" ) )
{
return '\'' + modelField.getDefaultValue() + '\'';
}
else if ( modelField.getType().equals( "long" ) )
{
return modelField.getDefaultValue() + 'L';
}
else if ( modelField.getType().equals( "float" ) )
{
return modelField.getDefaultValue() + 'f';
}
else if ( modelField.getType().equals( "Date" ) )
{
DateFormat format = new SimpleDateFormat( DEFAULT_DATE_FORMAT, Locale.US );
try
{
Date date = format.parse( modelField.getDefaultValue() );
return "new java.util.Date( " + date.getTime() + "L )";
}
catch ( ParseException pe )
{
throw new ModelloException( "Unparseable default date: " + modelField.getDefaultValue(), pe );
}
}
return modelField.getDefaultValue();
}
protected String getValueChecker( String type, String value, ModelField field )
throws ModelloException
{
String retVal;
if ( "boolean".equals( type ) || "double".equals( type ) || "float".equals( type ) || "int".equals( type )
|| "long".equals( type ) || "short".equals( type ) || "byte".equals( type ) || "char".equals( type ) )
{
retVal = "if ( " + value + " != " + getJavaDefaultValue( field ) + " )";
}
else if ( ModelDefault.LIST.equals( type ) || ModelDefault.SET.equals( type )
|| ModelDefault.MAP.equals( type ) || ModelDefault.PROPERTIES.equals( type ) )
{
retVal = "if ( ( " + value + " != null ) && ( " + value + ".size() > 0 ) )";
}
else if ( "String".equals( type ) && field.getDefaultValue() != null )
{
retVal = "if ( ( " + value + " != null ) && !" + value + ".equals( \"" + field.getDefaultValue() + "\" ) )";
}
else if ( "Date".equals( type ) && field.getDefaultValue() != null )
{
retVal = "if ( ( " + value + " != null ) && !" + value + ".equals( " + getJavaDefaultValue( field ) + " ) )";
}
else
{
retVal = "if ( " + value + " != null )";
}
return retVal;
}
}
modello-1.1/modello-plugins/modello-plugin-java/src/main/resources/ 0000755 0001750 0001750 00000000000 11260056267 024504 5 ustar mkoch mkoch modello-1.1/modello-plugins/modello-plugin-java/src/main/resources/META-INF/ 0000755 0001750 0001750 00000000000 11260056267 025644 5 ustar mkoch mkoch modello-1.1/modello-plugins/modello-plugin-java/src/main/resources/META-INF/plexus/ 0000755 0001750 0001750 00000000000 11260056267 027164 5 ustar mkoch mkoch modello-1.1/modello-plugins/modello-plugin-java/src/main/resources/META-INF/plexus/components.xml 0000644 0001750 0001750 00000001010 11127737506 032067 0 ustar mkoch mkoch