001: /**
002: * Redistribution and use of this software and associated documentation
003: * ("Software"), with or without modification, are permitted provided
004: * that the following conditions are met:
005: *
006: * 1. Redistributions of source code must retain copyright
007: * statements and notices. Redistributions must also contain a
008: * copy of this document.
009: *
010: * 2. Redistributions in binary form must reproduce the
011: * above copyright notice, this list of conditions and the
012: * following disclaimer in the documentation and/or other
013: * materials provided with the distribution.
014: *
015: * 3. The name "Exolab" must not be used to endorse or promote
016: * products derived from this Software without prior written
017: * permission of Intalio, Inc. For written permission,
018: * please contact info@exolab.org.
019: *
020: * 4. Products derived from this Software may not be called "Exolab"
021: * nor may "Exolab" appear in their names without prior written
022: * permission of Intalio, Inc. Exolab is a registered
023: * trademark of Intalio, Inc.
024: *
025: * 5. Due credit should be given to the Exolab Project
026: * (http://www.exolab.org/).
027: *
028: * THIS SOFTWARE IS PROVIDED BY INTALIO, INC. AND CONTRIBUTORS
029: * ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT
030: * NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
031: * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
032: * INTALIO, INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
033: * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
034: * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
035: * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
036: * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
037: * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
038: * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
039: * OF THE POSSIBILITY OF SUCH DAMAGE.
040: *
041: * Copyright 2001-2002 (C) Intalio, Inc. All Rights Reserved.
042: */package org.exolab.javasource;
043:
044: import java.io.File;
045: import java.io.FileWriter;
046: import java.io.IOException;
047: import java.util.Enumeration;
048: import java.util.Vector;
049:
050: /**
051: * This class represents the basic Java "structure" for a Java source file. This
052: * is the base class for JClass and JInterface.
053: * <br/>
054: * This is a useful utility when creating in memory source code. The code in
055: * this package was modelled after the Java Reflection API as much as possible
056: * to reduce the learning curve.
057: *
058: * @author <a href="mailto:skopp AT riege DOT de">Martin Skopp</a>
059: * @author <a href="mailto:keith AT kvisco DOT com">Keith Visco</a>
060: * @version $Revision: 6669 $ $Date: 2005-12-13 14:58:48 -0700 (Tue, 13 Dec 2005) $
061: */
062: public abstract class JStructure extends JType implements
063: JAnnotatedElement {
064: //--------------------------------------------------------------------------
065:
066: /** The Id for Source control systems.
067: * <br/>
068: * Note: I needed to break the String into parts to prevent CVS from expanding it here! */
069: private static final String DEFAULT_HEADER = "$" + "Id$";
070:
071: /** The source control version for listed in the JavaDoc
072: * <br/>
073: * Note: I needed to break the String into parts to prevent CVS from expanding it here! */
074: private static final String DEFAULT_VERSION = "$" + "Revision$ $"
075: + "Date$";
076:
077: /** A standard complaint for a bad parameter. */
078: private static final String JSW_SHOULD_NOT_BE_NULL = "argument 'jsw' should not be null.";
079:
080: //--------------------------------------------------------------------------
081:
082: /** The source header. */
083: private JComment _header;
084:
085: /** The package to which this JStructure belongs. */
086: private String _packageName;
087:
088: /** List of imported classes and packages. */
089: private Vector _imports;
090:
091: /** The Javadoc for this JStructure. */
092: private JDocComment _jdc;
093:
094: /** Implementation of JAnnoatedElement to delagate to. */
095: private JAnnotatedElementHelper _annotatedElement;
096:
097: /** The JModifiers for this JStructure, which allows us to change the resulting qualifiers. */
098: private JModifiers _modifiers;
099:
100: /** The set of interfaces implemented/extended by this JStructure. */
101: private Vector _interfaces;
102:
103: //--------------------------------------------------------------------------
104:
105: /**
106: * Creates a new JStructure with the given name.
107: *
108: * @param name The name of the JStructure.
109: */
110: protected JStructure(final String name) {
111: super (name);
112:
113: //-- verify name is a valid java class name
114: if (!isValidClassName(name)) {
115: String lname = getLocalName();
116: String err = "'" + lname + "' is ";
117: if (JNaming.isKeyword(lname)) {
118: err += "a reserved word and may not be used as a class name.";
119: } else {
120: err += "not a valid Java identifier.";
121: }
122: throw new IllegalArgumentException(err);
123: }
124:
125: _header = null;
126: _packageName = JNaming.getPackageFromClassName(name);
127: _imports = new Vector();
128: _jdc = new JDocComment(JDocDescriptor
129: .createVersionDesc(DEFAULT_VERSION));
130: _annotatedElement = new JAnnotatedElementHelper();
131: _modifiers = new JModifiers();
132: _interfaces = new Vector();
133: }
134:
135: /**
136: * Test the provided name and return true if it is a valid class name.
137: *
138: * @param classname A class name to test.
139: * @return True if the provided class name is a valid class name.
140: */
141: private boolean isValidClassName(final String classname) {
142: if (classname == null) {
143: return false;
144: }
145:
146: String name = classname;
147: int beforeTypeName = name.indexOf("<");
148: if (beforeTypeName > 0) {
149: name = name.substring(0, beforeTypeName);
150: }
151:
152: //-- ignore package information, for now
153: name = JNaming.getLocalNameFromClassName(name);
154:
155: return JNaming.isValidJavaIdentifier(name);
156: }
157:
158: //--------------------------------------------------------------------------
159:
160: /**
161: * Returns the JComment header to display at the top of the source file for
162: * this JStructure, or null if no header was set.
163: *
164: * @return The JComment header or null if none exists.
165: */
166: public final JComment getHeader() {
167: return _header;
168: }
169:
170: /**
171: * Sets the header comment for this JStructure.
172: *
173: * @param comment The comment to display at the top of the source file when printed.
174: */
175: public final void setHeader(final JComment comment) {
176: _header = comment;
177: }
178:
179: /**
180: * Returns the name of the package that this JStructure is a member of.
181: *
182: * @return The name of the package that this JStructure is a member of, or
183: * null if there is no current package name defined.
184: */
185: public final String getPackageName() {
186: return _packageName;
187: }
188:
189: /**
190: * Returns an Enumeration of imported package and class names for this
191: * JStructure.
192: *
193: * @return The Enumeration of imports. May be empty but will not be null.
194: */
195: public final Enumeration getImports() {
196: return _imports.elements();
197: }
198:
199: /**
200: * Returns true if the given classname exists in the imports of this
201: * JStructure.
202: *
203: * @param classname The class name to check for
204: * @return True if the given classname exists in the imports list.
205: */
206: public final boolean hasImport(final String classname) {
207: return _imports.contains(classname);
208: }
209:
210: /**
211: * Adds the given import to this JStructure. Note: You cannot import
212: * from the "default package," so imports with no package are ignored.
213: *
214: * @param className Name of the class to import.
215: */
216: public abstract void addImport(final String className);
217:
218: /**
219: * Adds the given import to this JStructure. Given class name should not be null or empty.
220: * <br/>
221: * Note: You cannot import from the "default package," so imports with no package are ignored.
222: *
223: * @param className Name of the class to import.
224: */
225: protected final void addImportInternal(final String className) {
226: //-- getPackageName
227: String pkgName = JNaming.getPackageFromClassName(className);
228:
229: if (pkgName != null) {
230: if (pkgName.equals(_packageName)
231: || pkgName.equals("java.lang")) {
232: return;
233: }
234:
235: //-- for readabilty keep import list sorted, and make sure
236: //-- we do not include more than one of the same import
237: for (int i = 0; i < _imports.size(); i++) {
238: String imp = (String) _imports.elementAt(i);
239: if (imp.equals(className)) {
240: return;
241: }
242: if (imp.compareTo(className) > 0) {
243: _imports.insertElementAt(className, i);
244: return;
245: }
246: }
247: _imports.addElement(className);
248: }
249: }
250:
251: /**
252: * Adds appropriate import for this JAnnotation.
253: *
254: * @param annotation A JAnnotation for which we want to add an import to
255: * this JStructure.
256: */
257: protected final void addImport(final JAnnotation annotation) {
258: addImport(annotation.getAnnotationType().getName());
259: }
260:
261: /**
262: * Adds appropriate imports for each JAnnotation in the given Array.
263: *
264: * @param annotations An Array of JAnnotation; we want to add an import to
265: * this JStructure for each JAnnotation in the Array.
266: */
267: protected final void addImport(final JAnnotation[] annotations) {
268: for (int i = 0; i < annotations.length; i++) {
269: addImport(annotations[i].getAnnotationType().getName());
270: }
271: }
272:
273: /**
274: * Remove the import of the given class name from this JStucture, returning
275: * true if the import was found and removed.
276: *
277: * @param className Name of the class to remove the import of.
278: * @return If the import was previously part of this JStructure, false
279: * otherwise.
280: */
281: public final boolean removeImport(final String className) {
282: boolean result = false;
283: if (className == null) {
284: return result;
285: }
286: if (className.length() == 0) {
287: return result;
288: }
289:
290: result = _imports.removeElement(className);
291: return result;
292: }
293:
294: /**
295: * Returns the JavaDoc comment for this JStructure.
296: *
297: * @return The JDocComment for this JStructure.
298: */
299: public final JDocComment getJDocComment() {
300: return _jdc;
301: }
302:
303: /**
304: * Returns the object managing the annotations for this JStructure.
305: *
306: * @return The object managing the annotations for this JStructure.
307: */
308: protected final JAnnotatedElementHelper getAnnotatedElementHelper() {
309: return _annotatedElement;
310: }
311:
312: /**
313: * {@inheritDoc}
314: */
315: public final boolean hasAnnotations() {
316: return _annotatedElement.hasAnnotations();
317: }
318:
319: /**
320: * {@inheritDoc}
321: */
322: public final JAnnotation[] getAnnotations() {
323: return _annotatedElement.getAnnotations();
324: }
325:
326: /**
327: * {@inheritDoc}
328: */
329: public final JAnnotation getAnnotation(
330: final JAnnotationType annotationType) {
331: return _annotatedElement.getAnnotation(annotationType);
332: }
333:
334: /**
335: * {@inheritDoc}
336: */
337: public final boolean isAnnotationPresent(
338: final JAnnotationType annotationType) {
339: return _annotatedElement.isAnnotationPresent(annotationType);
340: }
341:
342: /**
343: * {@inheritDoc}
344: */
345: public final void addAnnotation(final JAnnotation annotation) {
346: _annotatedElement.addAnnotation(annotation);
347: addImport(annotation);
348: }
349:
350: /**
351: * {@inheritDoc}
352: */
353: public final JAnnotation removeAnnotation(
354: final JAnnotationType annotationType) {
355: return _annotatedElement.removeAnnotation(annotationType);
356: }
357:
358: /**
359: * Returns the JModifiers, which allows the qualifiers to be changed.
360: *
361: * @return The JModifiers for this JStructure.
362: */
363: public final JModifiers getModifiers() {
364: return _modifiers;
365: }
366:
367: /**
368: * Returns an Enumeration of interface names that this JStructure inherits
369: * from.
370: *
371: * @return The Enumeration of interface names for this JStructure. May be
372: * empty but will not be null.
373: */
374: public final Enumeration getInterfaces() {
375: return _interfaces.elements();
376: }
377:
378: /**
379: * Return the count of the number of Interfaces that have been added to this
380: * JStructure.
381: *
382: * @return The count of the number of Interfaces that have been added to
383: * this JStructure.
384: */
385: protected final int getInterfaceCount() {
386: return _interfaces.size();
387: }
388:
389: /**
390: * Adds the given interface to the list of interfaces this JStructure
391: * inherits method declarations from, and either implements (JClass) or
392: * extends (JInterface).
393: *
394: * @param interfaceName The name of the interface to "inherit" method
395: * declarations from.
396: */
397: public final void addInterface(final String interfaceName) {
398: if (!_interfaces.contains(interfaceName)) {
399: _interfaces.addElement(interfaceName);
400: }
401: }
402:
403: //--------------------------------------------------------------------------
404:
405: /**
406: * Returns the field with the given name, or null if no field was found with
407: * that name.
408: *
409: * @param name The name of the field to return.
410: * @return The field with the given name, or null if no field was found with
411: * the given name.
412: */
413: public abstract JField getField(String name);
414:
415: /**
416: * Returns an array of all the JFields of this JStructure.
417: *
418: * @return An array of all the JFields of this JStructure.
419: */
420: public abstract JField[] getFields();
421:
422: /**
423: * Adds the given JField to this JStructure.
424: * <br/>
425: * This method is implemented by subclasses and should only accept the
426: * proper fields for the subclass otherwise an IllegalArgumentException will
427: * be thrown. For example a JInterface will only accept static fields.
428: *
429: * @param jField The JField to add.
430: */
431: public abstract void addField(JField jField);
432:
433: /**
434: * Adds the given JMember to this JStructure.
435: * <br/>
436: * This method is implemented by subclasses and should only accept the
437: * proper types for the subclass otherwise an IllegalArgumentException will
438: * be thrown.
439: *
440: * @param jMember The JMember to add to this JStructure.
441: */
442: public abstract void addMember(JMember jMember);
443:
444: //--------------------------------------------------------------------------
445:
446: /**
447: * Returns the name of the file that this JStructure would be printed to,
448: * given a call to {@link #print(String, String)}.
449: *
450: * @param destDir the destination directory. This may be null.
451: * @return the name of the file that this JInterface would be printed to
452: */
453: public final String getFilename(final String destDir) {
454: String filename = getLocalName() + ".java";
455:
456: //-- Convert Java package to path string
457: String javaPackagePath = "";
458: if ((_packageName != null) && (_packageName.length() > 0)) {
459: javaPackagePath = _packageName.replace('.',
460: File.separatorChar);
461: }
462:
463: //-- Create fully qualified path (including 'destDir') to file
464: File pathFile;
465: if (destDir == null) {
466: pathFile = new File(javaPackagePath);
467: } else {
468: pathFile = new File(destDir, javaPackagePath);
469: }
470: if (!pathFile.exists()) {
471: pathFile.mkdirs();
472: }
473:
474: //-- Prefix filename with path
475: if (pathFile.toString().length() > 0) {
476: filename = pathFile.toString() + File.separator + filename;
477: }
478:
479: return filename;
480: }
481:
482: //--------------------------------------------------------------------------
483:
484: /**
485: * Prints the source code for this JStructure to the destination directory.
486: * Subdirectories will be created if necessary for the package.
487: *
488: * @param destDir Directory name to use as the root directory for all output.
489: * @param lineSeparator The line separator to use at the end of each line.
490: * If null, then the default line separator for the runtime platform will be used.
491: */
492: public final void print(final String destDir,
493: final String lineSeparator) {
494: //-- open output file
495: String filename = getFilename(destDir);
496:
497: File file = new File(filename);
498: JSourceWriter jsw = null;
499: try {
500: jsw = new JSourceWriter(new FileWriter(file));
501: } catch (IOException ioe) {
502: System.out.println("unable to create class file: "
503: + filename);
504: return;
505: }
506: if (lineSeparator == null) {
507: jsw.setLineSeparator(System.getProperty("line.separator"));
508: } else {
509: jsw.setLineSeparator(lineSeparator);
510: }
511: print(jsw);
512: jsw.close();
513: }
514:
515: /**
516: * Prints the source code for this JStructure to the given JSourceWriter.
517: *
518: * @param jsw The JSourceWriter to print to.
519: */
520: public abstract void print(JSourceWriter jsw);
521:
522: /**
523: * A utility method that prints the header to the given JSourceWriter.
524: *
525: * @param jsw The JSourceWriter to print to.
526: */
527: public final void printHeader(final JSourceWriter jsw) {
528: if (jsw == null) {
529: throw new IllegalArgumentException(JSW_SHOULD_NOT_BE_NULL);
530: }
531:
532: //-- write class header
533: if (_header != null) {
534: _header.print(jsw);
535: } else {
536: jsw.writeln("/*");
537: jsw.writeln(" * " + DEFAULT_HEADER);
538: jsw.writeln(" */");
539: }
540: jsw.writeln();
541: jsw.flush();
542: }
543:
544: /**
545: * A utility method that prints the packageDeclaration to the given
546: * JSourceWriter.
547: *
548: * @param jsw The JSourceWriter to print to.
549: */
550: public final void printPackageDeclaration(final JSourceWriter jsw) {
551: if (jsw == null) {
552: throw new IllegalArgumentException(JSW_SHOULD_NOT_BE_NULL);
553: }
554:
555: //-- print package name
556: if ((_packageName != null) && (_packageName.length() > 0)) {
557: jsw.write("package ");
558: jsw.write(_packageName);
559: jsw.writeln(';');
560: jsw.writeln();
561: }
562: jsw.flush();
563: }
564:
565: /**
566: * A utility method that prints the imports to the given JSourceWriter.
567: *
568: * @param jsw The JSourceWriter to print to.
569: */
570: protected final void printImportDeclarations(final JSourceWriter jsw) {
571: if (jsw == null) {
572: throw new IllegalArgumentException(JSW_SHOULD_NOT_BE_NULL);
573: }
574:
575: //-- print imports
576: if (_imports.size() > 0) {
577: jsw.writeln(" //---------------------------------/");
578: jsw.writeln(" //- Imported classes and packages -/");
579: jsw.writeln("//---------------------------------/");
580: jsw.writeln();
581: Enumeration enumeration = _imports.elements();
582: while (enumeration.hasMoreElements()) {
583: jsw.write("import ");
584: jsw.write(enumeration.nextElement());
585: jsw.writeln(';');
586: }
587: jsw.writeln();
588: jsw.flush();
589: }
590: }
591:
592: /**
593: * {@inheritDoc}
594: * <br/>
595: * Returns the String representation of this JType.
596: */
597: public final String toString() {
598: return getName();
599: }
600:
601: //--------------------------------------------------------------------------
602: }
|