qdox-qdox-1.12.1/000077500000000000000000000000001204551233600135215ustar00rootroot00000000000000qdox-qdox-1.12.1/LICENSE.txt000066400000000000000000000011011204551233600153350ustar00rootroot00000000000000Copyright 2002-2009 Joe Walnes and QDox Project Team 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. qdox-qdox-1.12.1/README.txt000066400000000000000000000023051204551233600152170ustar00rootroot00000000000000To build QDox there are two prerequisites: * Maven 2 (2.0.9 or later) http://maven.apache.org * BYacc/J (1.8 or later) http://byaccj.sourceforge.net/ Paarser generator used to create an effective parser for JavaDoc. If using Windows, Linux, Solaris or Mac OS X, no additional installation is needed as yacc binaries are supplied in the bootstrap directory. If using any other platform, download BYacc/J from the site or build it yourself, in which case we would be grateful to receive a copy of your binary, so we can upgrade the bootstrap support. Build goals: mvn install - Create qdox jar mvn generate-sources - Generate the Java parser code (allowing you to develop in an IDE). mvn site - Build the QDox website mvn release:prepare - Prepare release (confirm or change release version interactively) mvn release:perform - Perform release (perform release from tag of prepare phase) If you are releasing, remember to 1) Update src/site/content/download.html 2) Go to JIRA and release the applicable version for QDOX : http://jira.codehaus.org/secure/project/ManageVersions.jspa?pid=10103 3) Copy the contents of target/site/ to the DAV folder for QDox's website : https://dav.codehaus.org/qdox/qdox-qdox-1.12.1/bootstrap/000077500000000000000000000000001204551233600155365ustar00rootroot00000000000000qdox-qdox-1.12.1/pom.xml000066400000000000000000000412461204551233600150450ustar00rootroot00000000000000 4.0.0 org.codehaus codehaus-parent 4 QDox com.thoughtworks.qdox qdox 1.12.1 http://qdox.codehaus.org QDox is a high speed, small footprint parser for extracting class/interface/method definitions from source files complete with JavaDoc @tags. It is designed to be used by active code generators or documentation tools. 2002 The Apache Software License, Version 2.0 http://www.apache.org/licenses/LICENSE-2.0.txt repo announce at QDox announce@qdox.codehaus.org announce-subscribe@qdox.codehaus.org announce-unsubscribe@qdox.codehaus.org http://archive.codehaus.org/lists/org.codehaus.qdox.announce dev at QDox dev@qdox.codehaus.org dev-subscribe@qdox.codehaus.org dev-unsubscribe@qdox.codehaus.org http://archive.codehaus.org/lists/org.codehaus.qdox.dev scm at QDox scm-subscribe@qdox.codehaus.org scm-unsubscribe@qdox.codehaus.org http://archive.codehaus.org/lists/org.codehaus.qdox.scm user at QDox user@qdox.codehaus.org user-subscribe@qdox.codehaus.org user-unsubscribe@qdox.codehaus.org http://archive.codehaus.org/lists/org.codehaus.qdox.user jira http://jira.codehaus.org/browse/QDOX scm:svn:http://svn.codehaus.org/qdox/tags/qdox-1.12.1 scm:svn:https://svn.codehaus.org/qdox/tags/qdox-1.12.1 http://svn.qdox.codehaus.org/browse/qdox/tags/qdox-1.12.1 rfscholte Robert Scholte +1 project lead joe Joe Walnes project founder Aslak Hellesoy rinkrank developer Paul Hammant paul developer Mike Williams mdub developer mauro Mauro Talevi developer Mike Royle Peter Donald James Strachan Nick Pomfret Chris Stevenson Ben Hogan Laurent Etiemble Shawn Chain Brian Slesinsky James Lee Eric Redmond org.apache.maven.wagon wagon-webdav 1.0-beta-2 ${basedir}/src/java ${basedir}/src/test ${basedir}/src/test-resources maven-clean-plugin 2.5 maven-surefire-plugin 2.4.2 maven-jar-plugin 2.4 maven-install-plugin 2.2 maven-deploy-plugin 2.3 de.jflex maven-jflex-plugin 1.4.3 generate ${project.build.directory}/generated-sources/parser ${basedir}/src/grammar/lexer.flex ${basedir}/src/grammar/skeleton.inner maven-antrun-plugin 1.3 OS Arch = ${os.arch} ${project.build.directory}/generated-sources/parser generate-sources generate-sources run org.apache.maven.plugins maven-compiler-plugin 2.0.2 1.4 1.4 UTF-8 org.apache.maven.plugins maven-javadoc-plugin 2.4 attach-javadoc package jar http://java.sun.com/j2se/1.5/docs/api org.apache.maven.plugins maven-assembly-plugin 2.2-beta-5 project make-assembly package single maven-site-plugin 3.2 ${basedir}/src/site/templates/site-template.vm org.codehaus.xsite xsite-maven-plugin 1.0 content/website.xml templates/skin.html ${xsite.sourceDirectoryPath} ${project.build.directory}/site resources site run maven-resources-plugin 2.3 pre-copy-resources pre-site copy-resources ${xsite.sourceDirectoryPath} src/site **/download.html **/skin.html src/site **/download.html **/skin.html true post-copy-resources site copy-resources ${project.build.directory}/site ${xsite.sourceDirectoryPath}/content images/*.* apidocs/**/*.* org.apache.maven.plugins maven-release-plugin 2.3.2 deploy ant ant 1.5.1 compile true junit junit 3.8.1 compile true jmock jmock 1.0.0 test codehaus.org QDox Site dav:https://dav.codehaus.org/qdox/ linux Linux i386 ${basedir}/bootstrap/yacc.linux linux64 Linux amd64 ${basedir}/bootstrap/yacc.linux.x86_64 solaris SunOS ${basedir}/bootstrap/yacc.solaris macosx Mac ${basedir}/bootstrap/yacc.macosx windows Windows ${basedir}/bootstrap/yacc.exe ${xsite.sourceDirectoryPath}/content org.apache.maven.plugins maven-project-info-reports-plugin 2.1 dependencies project-team mailing-list issue-tracking license scm summary org.codehaus.mojo cobertura-maven-plugin 2.2 org.apache.maven.plugins maven-javadoc-plugin 2.4 com.thoughtworks.qdox.* true true ${project.name} ${project.version} API UTF-8 org.apache.maven.plugins maven-changes-plugin 2.1 %URL%/%ISSUE% changes-report yyyy-MM-dd ${maven.build.timestamp} ${project.build.directory}/generated-site qdox-qdox-1.12.1/src/000077500000000000000000000000001204551233600143105ustar00rootroot00000000000000qdox-qdox-1.12.1/src/changes/000077500000000000000000000000001204551233600157205ustar00rootroot00000000000000qdox-qdox-1.12.1/src/changes/changes.xml000066400000000000000000000471321204551233600200610ustar00rootroot00000000000000 Changes Joe Walnes AbstractJavaEntity#getCodeBlock() skips Javadoc separator Unwanted DocletTag.getParameters()[0]=< in generic case Multilined tag attribute values not working anymore Parsing JavadocComment improvement Add method to safely and easily get the package name for a JavaClass Retaining whitespace in comments QDox Site overhaul Introduce toString() according to the Java Language Specification JavaClass.getFullyQualifiedName() does not work on version 1.9 (version 1.6.3 works without problem). Manual resolve scanning imports are required Annotation parsing fails on enum constant when javadoc present Annotation with comment can't be parsed Better handler of generics in Type JavaField#getInitializationExpression() is wrong for char ParseException when using annotations in methods Parser fails to translate Unicode escapes Qdox fails to parse enums inside class QDOX-156 Remove single comment in JavaField#getInitializationExpression() Wrong whitespace in JavaField#getInitializationExpression() error parsing clauses with indexOf most simple annotation, like @Override, results in a parseexception make use of maven-jflex-plugin instead of an antrun getInitializationExpression() includes comment text More package information, not just package name. Parser fails on package with annotations QDox fails to parse correct code Annotation with value in method signature does not parse Annotations With Parameters do not work Field modifiers of binary classes ignored Multiple annotations on one field and generics Name resolution of imported nested types does not work correctly ParseException for private static String[] allConstants = {C1,C2,C3}; Parser fails depending on the position of an internal enum Performance Improvement of JavaDocBuilder.getClassByName() Static block source code gets associated with source code of subsequent method Support for retrieval of generic type information (JSR 14) add parser support for enumerated types annotation value poluted with class instance block inner classes not resolved correctly when appears as method param packaging with java5+ fails due to incorrect javadocs Improved annotation support including types, fields and expressions. Fix to lexer bug. Inconsistency between getMethods(), getFields() in binary and source JavaClass fixed. Project version control web page shows CVS instead of SVN. Migrate site to use XSite. Improved generic parsing support. Also fixes QDOX-108. Improved annotation parsing support. Improved anon inner class parsing support. Maven2 support. Original body of method can be obtained using JavaMethod.getSourceCode(). Original field initialization expression can be obtained by JavaField.getInitializationExpression(). Improved Enum parsing support. Switched license from 'Ironsmith' Apache license clone to genuine Apache 2 license. Provide line numbers for all java entities. Ensure that things (e.g. named tag-parameters, bean-properties) are consistently returned in declared order. Support for wildcard generic-type arguments. Convenience methods - Type.isPrimitive() and Type.isVoid(). Parser can now handle Java 5 annotations. Support for generic-type parameters on methods. Support for Java 5 varargs syntax: "printf(Object... stuff)". New method, JavaParameter.isVarArgs(). JavaDoc comments now preserve end of line characters. Support legal Unicode characters in identifiers. Inner/nested classes are now resolved correctly between packages. Correct terminology re "inner" vs "nested" classes. Reinstate public constructors on concrete model classes. Support for methods that specify array dimensions at end: String doStuff()[] Static blocks do not add static modifier to next method. Support for trailing semicolon after class definition. Bugfix: Support for empty /**/ comments. Patch from Mario Siegenthaler and Daniel Müller to improve tolerance of Java 5 syntax, including: annotations with classes as parameters, generic field initialization, static imports and enums with enumeration ending with a semicolon. Added QDoxTester to test that QDox can successfully parse a load of Java source. Refactor DocletTag handling so that all context information is provided via the DocletTagFactory. Add support for parsing of JSR-14 generic types. Also fixes QDOX-50. Improve parsing of tag parameters, particularly where whitespace is involved. Fixed generation of Eclipse ".classpath". Problems compiling against jmock-1.0.0. Handle extra stars in Javadoc start/end tokens. Handle unclosed quotes in tag values. Support for strictfp modifier (and volatile and native). JavaClass.getTagsByName() is buggy. recursive retrieval of tags from superclasses got a bug. Also fixes QDOX-37: Handle inner-classes in type-resolution. Support multiple fields in a single field-declaration. Throw a ParseException, including location info, if a syntax error is encountered. Fix handling of MAC line-endings. Allow "$" in identifiers. Added DocletTag.getNamedParameterMap(). Added JavaField.getDeclarationSignature(). Support for binary classes. Support for bean properties. New isA(String fullyQualifiedName) method in JavaClass. Pluggable DocletTag implementations via DocletTagFactory. This opens up for tag validation, ${property} substitution and other goodies that shouldn't go directly into QDox' core, but rather into pluggable extensions. Line numbers in the lexer. resolveTypeInternal doesn't work for nested types. JavaMethod.equals() failed for constructors. BeanProperty : support for type retrieval. Also fixes QDOX-19. More robust handling of "*" and "@" in Javadoc body. Encoding support for internationalization. Type now has a getJavaClass() method making it easier to find the JavaClass of a Type from e.g. Velocity. Example: $method.returns.javaClass Implemented tag inheritance on classes and methods. (It makes no sense to have it on fields or constructors). Accessed with clazz|method.getTag[s]ByName(String name, boolean superclasses). DocletTag is an interface. Added a getClasses() method to JavaDocBuilder that will return all JavaClasses. Added a getDerivedClasses() method to JavaClass that will return all derived classes, i.e. subclasses or subinterfaces. Added getDeclarationSignature() and getCallSignature() methods to JavaMethod. Added a getNamedParameter(String tagName, String parameterName) convenience method to AbstractJavaEntity for easier retrieval of tag parameters without having to null-check the tag. Added APITestCase. This is a JUnit extension that can be used to compare the equality of two Java sources on the API level. Added int getLineNumber() to DocletTag. Added JavaSource getJavaSource() to DocletTag. Added boolean isInner() to JavaClass. Added JavaMethod[] getMethods(boolean superclasses) to JavaClass. Quoted tokens allowed in doclet tags. Asterix symbol allowed in doclet tags. Added support for inner classes. Moved build system over to Maven. Initial release. qdox-qdox-1.12.1/src/grammar/000077500000000000000000000000001204551233600157365ustar00rootroot00000000000000qdox-qdox-1.12.1/src/grammar/lexer.flex000066400000000000000000000363771204551233600177550ustar00rootroot00000000000000// class headers package com.thoughtworks.qdox.parser.impl; import com.thoughtworks.qdox.parser.*; %% // class and lexer definitions %class JFlexLexer %public %implements Lexer %byaccj %unicode %line %column %{ private int classDepth = 0; private int parenDepth = 0; private int nestingDepth = 0; private int annotationDepth = 0; private int assignmentDepth = 0; private int stateDepth = 0; private int codeblockDepth = 0; private int[] stateStack = new int[10]; private int braceMode = CODEBLOCK; private int parenMode = -1; private String className; private boolean javaDocNewLine; private boolean javaDocStartedContent; private StringBuffer codeBody = new StringBuffer(8192); private boolean newMode; private boolean bracketMode; private boolean anonymousMode; private boolean appendingToCodeBody; private boolean shouldCaptureCodeBody; private boolean isConstructor; public void setCaptureCodeBody(boolean shouldCaptureCodeBody) { this.shouldCaptureCodeBody = shouldCaptureCodeBody; } public String text() { return yytext(); } public int lex() throws java.io.IOException { return yylex(); } public int getLine() { return yyline + 1; } public int getColumn() { return yycolumn + 1; } private void pushState(int newState) { stateStack[stateDepth++] = zzLexicalState; yybegin(newState); } private void popState() { yybegin(stateStack[--stateDepth]); } private int peekState(int relative) { if(relative > stateDepth) { return -1; } else { return stateStack[stateDepth - relative]; } } public String getCodeBody(){ String s = codeBody.toString(); codeBody = new StringBuffer(8192); return s; } %} Eol = \r|\n|\r\n WhiteSpace = {Eol} | [ \t\f] CommentChar = ( [^ \t\r\n*] | "*"+ [^ \t\r\n/*] ) IntegerLiteral = (( [1-9] ([0-9])* ) | ( "0" [xX] ([0-9]|[a-f]|[A-F])+ ) | ( "0" ([0-7])* )) LongLiteral = (( [1-9] ([0-9])* ) | ( "0" [xX] ([0-9]|[a-f]|[A-F])+ ) | ( "0" ([0-7])* )) [lL] Exponent = [eE] [+-]? ([0-9])+ FloatLiteral = ( [0-9]+ ("." [0-9]+)? ({Exponent})? ([fF])? ) | ( "." [0-9]+ ({Exponent})? ([fF])? ) | ( ([0-9])+ {Exponent} ([fF])? ) | ( ([0-9])+ ({Exponent})? [fF] ) DoubleLiteral = ( [0-9]+ ("." [0-9]+)? ({Exponent})? [dD] ) | ( "." [0-9]+ ({Exponent})? [dD] ) | ( ([0-9])+ {Exponent} [dD] ) | ( ([0-9])+ ({Exponent})? [dD] ) UnicodeChar = \\u[a-fA-F0-9]{4} Id = ([:jletter:]|{UnicodeChar}) ([:jletterdigit:]|{UnicodeChar})* Annotation = "@" {WhiteSpace}* {Id} ("."{Id})* {WhiteSpace}* JavadocEnd = "*"+ "/" %state JAVADOC JAVADOCTAG JAVADOCLINE CODEBLOCK PARENBLOCK ASSIGNMENT STRING CHAR SINGLELINECOMMENT MULTILINECOMMENT ANNOTATION ANNOSTRING ANNOCHAR ENUM %% { "." { return Parser.DOT; } "..." { return Parser.DOTDOTDOT; } "," { return Parser.COMMA; } "*" { return Parser.STAR; } "package" { return Parser.PACKAGE; } "import" { return Parser.IMPORT; } "public" { return Parser.PUBLIC; } "protected" { return Parser.PROTECTED; } "private" { return Parser.PRIVATE; } "static" { return Parser.STATIC; } "final" { return Parser.FINAL; } "abstract" { return Parser.ABSTRACT; } "native" { return Parser.NATIVE; } "strictfp" { return Parser.STRICTFP; } "synchronized" { return Parser.SYNCHRONIZED; } "transient" { return Parser.TRANSIENT; } "volatile" { return Parser.VOLATILE; } "throws" { return Parser.THROWS; } "extends" { return Parser.EXTENDS; } "implements" { return Parser.IMPLEMENTS; } "super" { return Parser.SUPER; } "[" { nestingDepth++; return Parser.SQUAREOPEN; } "]" { nestingDepth--; return Parser.SQUARECLOSE; } ")" { nestingDepth--; return Parser.PARENCLOSE; } "<" { return Parser.LESSTHAN; } ">" { return Parser.GREATERTHAN; } "&" { return Parser.AMPERSAND; } "?" { return Parser.QUERY; } "@" {WhiteSpace}* "interface" { classDepth++; braceMode = YYINITIAL; return Parser.ANNOINTERFACE; } "class" { classDepth++; braceMode = YYINITIAL; return Parser.CLASS; } "interface" { classDepth++; braceMode = YYINITIAL; return Parser.INTERFACE; } "enum" { classDepth++; braceMode = ENUM; return Parser.ENUM; } {Annotation} "(" { parenMode = ANNOTATION; yypushback(text().length()-1); getCodeBody(); /* reset codebody */ return Parser.AT; } "@" { return Parser.AT; } "{" { if(braceMode >= 0) { if(braceMode == ENUM) { isConstructor = true; } else if (braceMode == CODEBLOCK) { getCodeBody(); /* reset codebody */ appendingToCodeBody = true; } pushState(braceMode); braceMode = -1; yypushback(1); /* (re)enter brace in right mode */ } else { nestingDepth++; braceMode = CODEBLOCK; return Parser.BRACEOPEN; } } "}" { nestingDepth--; classDepth--; popState(); braceMode = CODEBLOCK; return Parser.BRACECLOSE; } "/**" ~"*/" { pushState(JAVADOC); yypushStream(new java.io.StringReader(text().substring(2))); return Parser.JAVADOCSTART; } "=" {WhiteSpace}* { assignmentDepth = nestingDepth; getCodeBody(); /* reset codebody */ appendingToCodeBody = true; pushState(ASSIGNMENT); } "default" { assignmentDepth = nestingDepth; appendingToCodeBody = true; pushState(ASSIGNMENT); } {Id} { return Parser.IDENTIFIER; } } { ";" { return Parser.SEMI; } "(" { nestingDepth++; if( parenMode >= 0 ) { annotationDepth = nestingDepth; pushState(parenMode); parenMode = -1; } return Parser.PARENOPEN; } } { ";" { isConstructor = false; return Parser.SEMI; } "(" { nestingDepth++; if(parenMode >= 0) { annotationDepth = nestingDepth; pushState(parenMode); parenMode = -1; return Parser.PARENOPEN; } else { if(isConstructor) { parenDepth = classDepth; pushState(PARENBLOCK); return Parser.PARENBLOCK; } else { return Parser.PARENOPEN; } } } } { "@" { yypushback(1); pushState(JAVADOCTAG); } [^ \t\r*@] { yypushback(1); pushState(JAVADOCLINE); } "*"+ [ \t]* / "@" { pushState(JAVADOCTAG); } "*"+ [ \t]? { pushState(JAVADOCLINE); } {JavadocEnd} { popState(); yypopStream(); return Parser.JAVADOCEND; } } { ~{Eol} { popState(); return Parser.JAVADOCLINE; } .* [^ \t*] / [ \t]* {JavadocEnd} { popState(); return Parser.JAVADOCLINE;} {JavadocEnd} { popState(); popState(); yypopStream(); return Parser.JAVADOCEND; } } { "@" [^ \t\n\r]+ / {JavadocEnd} { popState(); return Parser.JAVADOCTAG; } "@" [^ \t\n\r]+ { return Parser.JAVADOCTAG; } [ \t]+ { popState();pushState(JAVADOCLINE);} {Eol} { popState();return Parser.JAVADOCLINE;} } { "{" { if(codeblockDepth++ > 0 ) { codeBody.append('{'); } } "}" { if (--codeblockDepth == 0) { popState(); appendingToCodeBody = false; braceMode = CODEBLOCK; return Parser.CODEBLOCK; } else { codeBody.append('}'); } } } { "(" { ++ nestingDepth; return Parser.PARENOPEN; } ")" { if( nestingDepth-- == annotationDepth) { popState(); } return Parser.PARENCLOSE; } "," { return Parser.COMMA; } "=" { return Parser.EQUALS; } "{" { nestingDepth++; return Parser.BRACEOPEN; } "}" { nestingDepth--; return Parser.BRACECLOSE; } "\"" { appendingToCodeBody=true; codeBody.append("\""); pushState(ANNOSTRING); } "\'" { appendingToCodeBody=true; codeBody.append("\'"); pushState(ANNOCHAR); } "." { return Parser.DOT; } "?" { return Parser.QUERY; } ":" { return Parser.COLON; } "<<" { return Parser.LESSTHAN2; } ">>>" { return Parser.GREATERTHAN3; } ">>" { return Parser.GREATERTHAN2; } "==" { return Parser.EQUALS2; } "!=" { return Parser.NOTEQUALS; } "<" { return Parser.LESSTHAN; } ">" { return Parser.GREATERTHAN; } "<=" { return Parser.LESSEQUALS; } ">=" { return Parser.GREATEREQUALS; } "*" { return Parser.STAR; } "/" { return Parser.SLASH; } "%" { return Parser.PERCENT; } "+" { return Parser.PLUS; } "-" { return Parser.MINUS; } "byte" { return Parser.BYTE; } "char" { return Parser.CHAR; } "short" { return Parser.SHORT; } "int" { return Parser.INT; } "long" { return Parser.LONG; } "float" { return Parser.FLOAT; } "double" { return Parser.DOUBLE; } "&&" { return Parser.AMPERSAND2; } "||" { return Parser.VERTLINE2; } "!" { return Parser.EXCLAMATION; } "&" { return Parser.AMPERSAND; } "|" { return Parser.VERTLINE; } "^" { return Parser.CIRCUMFLEX; } "~" { return Parser.TILDE; } {IntegerLiteral} { return Parser.INTEGER_LITERAL; } {LongLiteral} { return Parser.LONG_LITERAL; } {FloatLiteral} { return Parser.FLOAT_LITERAL; } {DoubleLiteral} { return Parser.DOUBLE_LITERAL; } "true" | "false" { return Parser.BOOLEAN_LITERAL; } "class" { return Parser.CLASS; } {Id} { return Parser.IDENTIFIER; } "@" { return Parser.AT; } } { "\"" { codeBody.append("\""); popState(); appendingToCodeBody=false; return Parser.STRING_LITERAL; } "\\\"" { codeBody.append("\\\""); } "\\\\" { codeBody.append("\\\\"); } } { \' { codeBody.append("\'"); popState(); appendingToCodeBody=false; return Parser.CHAR_LITERAL; } "\\'" { codeBody.append("\\'"); } "\\\\" { codeBody.append("\\\\"); } } { "(" { nestingDepth++; if (appendingToCodeBody) { codeBody.append("("); } } ")" { nestingDepth--; if (appendingToCodeBody) { codeBody.append(")"); } if (nestingDepth == parenDepth) { popState(); } } } { ";" { if (nestingDepth == assignmentDepth) { appendingToCodeBody = true; newMode = false; popState(); return Parser.SEMI; } else { codeBody.append(';'); } } "," { if (nestingDepth == assignmentDepth) { appendingToCodeBody = true; popState(); return Parser.COMMA; } else { codeBody.append(','); } } "{" { codeBody.append('{'); anonymousMode = true; nestingDepth++; } "}" { codeBody.append('}'); if (anonymousMode) { nestingDepth--; if (nestingDepth==assignmentDepth) { anonymousMode=false; } } } "(" { codeBody.append('('); parenDepth = nestingDepth++; pushState(PARENBLOCK); } ")" { codeBody.append(')'); nestingDepth--; if (nestingDepth < assignmentDepth) { appendingToCodeBody = true; popState(); return Parser.PARENCLOSE; } } "[" { codeBody.append('['); bracketMode = true; nestingDepth++; } "]" { codeBody.append(']'); bracketMode = false; nestingDepth--; } "new" { codeBody.append("new"); if (nestingDepth==assignmentDepth) { newMode=true; } } "." [ \t\r\n]* / "<" { codeBody.append('.'); newMode = true; } "<" { codeBody.append('<'); if (!bracketMode && newMode && !anonymousMode) { nestingDepth++; } } ">" { codeBody.append('>'); if (!anonymousMode) { if (!bracketMode && newMode) { nestingDepth--; if (nestingDepth==assignmentDepth) { newMode=false; } } } } } { "\"" { if (appendingToCodeBody) { codeBody.append('"'); } pushState(STRING); } \' { if (appendingToCodeBody) { codeBody.append('\''); } pushState(CHAR); } } { "//" { if (appendingToCodeBody) { codeBody.append("//"); } pushState(SINGLELINECOMMENT); } "/*" { if (appendingToCodeBody) { codeBody.append("/*"); } pushState(MULTILINECOMMENT); } "/**/" { if (appendingToCodeBody) { codeBody.append("/**/"); } } } { .|{WhiteSpace} { codeBody.append(yytext()); } } { "\"" { if (appendingToCodeBody) { codeBody.append('"'); } popState(); } "\\\"" { if (appendingToCodeBody) { codeBody.append("\\\""); } } "\\\\" { if (appendingToCodeBody) { codeBody.append("\\\\"); } } } { \' { if (appendingToCodeBody) { codeBody.append('\''); } popState(); } "\\'" { if (appendingToCodeBody) { codeBody.append("\\'"); } } "\\\\" { if (appendingToCodeBody) { codeBody.append("\\\\"); } } } { {Eol} { if (appendingToCodeBody) { codeBody.append(yytext()); } popState(); } } { "*/" { if (appendingToCodeBody) { codeBody.append("*/"); } popState(); } } .|\r|\n|\r\n { if (appendingToCodeBody) { codeBody.append(yytext()); } } qdox-qdox-1.12.1/src/grammar/parser.y000066400000000000000000000563621204551233600174400ustar00rootroot00000000000000%{ import com.thoughtworks.qdox.parser.*; import com.thoughtworks.qdox.parser.structs.*; import com.thoughtworks.qdox.model.*; import com.thoughtworks.qdox.model.annotation.*; import java.io.IOException; import java.util.LinkedList; import java.util.ArrayList; import java.util.List; import java.util.Stack; %} %token SEMI DOT DOTDOTDOT COMMA STAR PERCENT EQUALS ANNOSTRING ANNOCHAR SLASH PLUS MINUS %token PACKAGE IMPORT PUBLIC PROTECTED PRIVATE STATIC FINAL ABSTRACT NATIVE STRICTFP SYNCHRONIZED TRANSIENT VOLATILE %token CLASS INTERFACE ENUM ANNOINTERFACE THROWS EXTENDS IMPLEMENTS SUPER DEFAULT %token BRACEOPEN BRACECLOSE SQUAREOPEN SQUARECLOSE PARENOPEN PARENCLOSE %token LESSTHAN GREATERTHAN LESSEQUALS GREATEREQUALS %token LESSTHAN2 GREATERTHAN2 GREATERTHAN3 %token EXCLAMATION AMPERSAND2 VERTLINE2 EQUALS2 NOTEQUALS %token TILDE AMPERSAND VERTLINE CIRCUMFLEX %token VOID %token QUERY COLON AT %token JAVADOCSTART JAVADOCEND JAVADOCEOL %token CODEBLOCK PARENBLOCK %token BYTE SHORT INT LONG CHAR FLOAT DOUBLE BOOLEAN // strongly typed tokens/types %token IDENTIFIER JAVADOCTAG JAVADOCLINE %token BOOLEAN_LITERAL %token INTEGER_LITERAL %token LONG_LITERAL %token FLOAT_LITERAL %token DOUBLE_LITERAL %token CHAR_LITERAL %token STRING_LITERAL %token VERTLINE2 AMPERSAND2 VERTLINE CIRCUMFLEX AMPERSAND EQUALS2 NOTEQUALS %token LESSTHAN GREATERTHAN LESSEQUALS GREATEREQUALS LESSTHAN2 GREATERTHAN2 GREATERTHAN3 %token PLUS MINUS STAR SLASH PERCENT TILDE EXCLAMATION %type name primitiveType %type value expression literal annotation arrayInitializer %type conditionalExpression conditionalOrExpression conditionalAndExpression inclusiveOrExpression exclusiveOrExpression andExpression %type equalityExpression relationalExpression shiftExpression additiveExpression multiplicativeExpression %type unaryExpression unaryExpressionNotPlusMinus primary %type dims %type fullidentifier modifier typedeclspecifier typename memberend %type dimensions %type varargs %type type arrayidentifier classtype typearg %% // ----- TOP LEVEL // A file consists of 0-n fileparts... file: | file { line = lexer.getLine(); } filepart; // And a filepart is a package/import statement, javadoc comment, or class declaration. filepart: annotation { builder.addAnnotation((Annotation) $1); } | package | import | javadoc | class | enum | SEMI; // Package statement package: PACKAGE fullidentifier SEMI { builder.addPackage(new PackageDef($2, line)); }; // Import statement import: IMPORT fullidentifier SEMI { builder.addImport($2); } | IMPORT STATIC fullidentifier SEMI { builder.addImport("static " + $3); }; // ----- JAVADOC javadoclist: javadoc | javadoclist javadoc; javadoc: JAVADOCSTART javadocdescription javadoctags JAVADOCEND; javadocdescription: javadoctokens { builder.addJavaDoc(buffer()); }; javadoctokens: | javadoctokens javadoctoken; javadoctoken: JAVADOCLINE { appendToBuffer($1); } javadoctags: | javadoctags javadoctag; javadoctag: JAVADOCTAG { line = lexer.getLine(); } javadoctokens { builder.addJavaDocTag(new TagDef($1.substring(1), buffer(), line)); }; // ----- COMMON TOKENS // A fullidentifier is "a", "a.b", "a.b.c", "a.b.*", etc... fullidentifier: IDENTIFIER { $$ = $1; } | fullidentifier DOT IDENTIFIER { $$ = $1 + '.' + $3; } | fullidentifier DOT STAR { $$ = $1 + ".*"; }; arrayidentifier: IDENTIFIER dimensions { $$ = new TypeDef($1,$2); }; dimensions: /* empty */ { $$ = 0; } | dimensions SQUAREOPEN SQUARECLOSE { $$ = $1 + 1; }; // Modifiers to methods, fields, classes, interfaces, parameters, etc... modifier: PUBLIC { $$ = "public"; } | PROTECTED { $$ = "protected"; } | PRIVATE { $$ = "private"; } | STATIC { $$ = "static"; } | FINAL { $$ = "final"; } | ABSTRACT { $$ = "abstract"; } | NATIVE { $$ = "native"; } | SYNCHRONIZED { $$ = "synchronized"; } | VOLATILE { $$ = "volatile"; } | TRANSIENT { $$ = "transient"; } | STRICTFP { $$ = "strictfp"; } ; modifiers: modifiers modifier { modifiers.add($2); } | modifiers annotation { builder.addAnnotation((Annotation) $2); } | modifiers javadoc | ; //-------------------------------------------------------------------------------- // ANNOTATIONS //-------------------------------------------------------------------------------- annotation: AT name { annotationStack.add(annotation); annotation = new Annotation(builder.createType($2, 0), lexer.getLine()); } annotationParensOpt { $$ = annotation; annotation = (Annotation)annotationStack.remove(annotationStack.size() - 1); }; annotationParensOpt: | PARENOPEN value PARENCLOSE { annotation.setProperty("value", $2); } | PARENOPEN valuePairs PARENCLOSE | PARENOPEN PARENCLOSE; valuePairs: valuePair | valuePairs COMMA valuePair; valuePair: IDENTIFIER EQUALS value { annotation.setProperty($1, $3); }; arrayInitializer: { annoValueListStack.add(annoValueList); annoValueList = new ArrayList(); } BRACEOPEN valuesOpt BRACECLOSE { $$ = new AnnotationValueList(annoValueList); annoValueList = (List)annoValueListStack.remove(annoValueListStack.size() - 1); }; valuesOpt: | values; values: value { annoValueList.add($1); } | values COMMA value { annoValueList.add($3); }; value: expression { $$ = $1; } | annotation { $$ = $1; } | arrayInitializer { $$ = $1; }; expression: conditionalExpression { $$ = $1; }; conditionalExpression: conditionalOrExpression { $$ = $1; } | conditionalOrExpression QUERY expression COLON expression { $$ = new AnnotationQuery($1, $3, $5); }; conditionalOrExpression: conditionalAndExpression { $$ = $1; } | conditionalOrExpression VERTLINE2 conditionalAndExpression { $$ = new AnnotationLogicalOr($1, $3); }; conditionalAndExpression: inclusiveOrExpression { $$ = $1; } | conditionalAndExpression AMPERSAND2 inclusiveOrExpression { $$ = new AnnotationLogicalAnd($1, $3); }; inclusiveOrExpression: exclusiveOrExpression { $$ = $1; } | inclusiveOrExpression VERTLINE exclusiveOrExpression { $$ = new AnnotationOr($1, $3); }; exclusiveOrExpression: andExpression { $$ = $1; } | exclusiveOrExpression CIRCUMFLEX andExpression { $$ = new AnnotationExclusiveOr($1, $3); }; andExpression: equalityExpression { $$ = $1; } | andExpression AMPERSAND equalityExpression { $$ = new AnnotationAnd($1, $3); }; equalityExpression: relationalExpression { $$ = $1; } | equalityExpression EQUALS2 relationalExpression { $$ = new AnnotationEquals($1, $3); } | equalityExpression NOTEQUALS relationalExpression { $$ = new AnnotationNotEquals($1, $3); }; relationalExpression: shiftExpression { $$ = $1; } | relationalExpression LESSEQUALS shiftExpression { $$ = new AnnotationLessEquals($1, $3); } | relationalExpression GREATEREQUALS shiftExpression { $$ = new AnnotationGreaterEquals($1, $3); } | relationalExpression LESSTHAN shiftExpression { $$ = new AnnotationLessThan($1, $3); } | relationalExpression GREATERTHAN shiftExpression { $$ = new AnnotationGreaterThan($1, $3); }; shiftExpression: additiveExpression { $$ = $1; } | shiftExpression LESSTHAN2 additiveExpression { $$ = new AnnotationShiftLeft($1, $3); } | shiftExpression GREATERTHAN3 additiveExpression { $$ = new AnnotationUnsignedShiftRight($1, $3); } | shiftExpression GREATERTHAN2 additiveExpression { $$ = new AnnotationShiftRight($1, $3); }; additiveExpression: multiplicativeExpression { $$ = $1; } | additiveExpression PLUS multiplicativeExpression { $$ = new AnnotationAdd($1, $3); } | additiveExpression MINUS multiplicativeExpression { $$ = new AnnotationSubtract($1, $3); }; multiplicativeExpression: unaryExpression { $$ = $1; } | multiplicativeExpression STAR unaryExpression { $$ = new AnnotationMultiply($1, $3); } | multiplicativeExpression SLASH unaryExpression { $$ = new AnnotationDivide($1, $3); } | multiplicativeExpression PERCENT unaryExpression { $$ = new AnnotationRemainder($1, $3); }; unaryExpression: PLUS unaryExpression { $$ = new AnnotationPlusSign($2); } | MINUS unaryExpression { $$ = new AnnotationMinusSign($2); } | unaryExpressionNotPlusMinus { $$ = $1; }; unaryExpressionNotPlusMinus: TILDE unaryExpression { $$ = new AnnotationNot($2); } | EXCLAMATION unaryExpression { $$ = new AnnotationLogicalNot($2); } | primary; primary: PARENOPEN primitiveType PARENCLOSE unaryExpression { $$ = new AnnotationCast(builder.createType($2, 0), $4); } | PARENOPEN primitiveType dims PARENCLOSE unaryExpression { $$ = new AnnotationCast(builder.createType($2, $3), $5); } | PARENOPEN name dims PARENCLOSE unaryExpressionNotPlusMinus { $$ = new AnnotationCast(builder.createType($2, $3), $5); } | PARENOPEN name PARENCLOSE unaryExpressionNotPlusMinus { $$ = new AnnotationCast(builder.createType($2, 0), $4); } | PARENOPEN expression PARENCLOSE { $$ = new AnnotationParenExpression($2); } | literal { $$ = $1; } | primitiveType dims DOT CLASS { $$ = new AnnotationTypeRef(builder.createType($1, 0)); } | primitiveType DOT CLASS { $$ = new AnnotationTypeRef(builder.createType($1, 0)); } | name DOT CLASS { $$ = new AnnotationTypeRef(builder.createType($1, 0)); } | name dims DOT CLASS { $$ = new AnnotationTypeRef(builder.createType($1, 0)); } | name { $$ = new AnnotationFieldRef($1); }; dims: SQUAREOPEN SQUARECLOSE { $$ = 1; } | dims SQUAREOPEN SQUARECLOSE { $$ = $1 + 1; }; name: IDENTIFIER { $$ = $1; } | name DOT IDENTIFIER { $$ = $1 + "." + $3; }; literal: DOUBLE_LITERAL { $$ = new AnnotationConstant(toDouble($1), $1); } | FLOAT_LITERAL { $$ = new AnnotationConstant(toFloat($1), $1); } | LONG_LITERAL { $$ = new AnnotationConstant(toLong($1), $1); } | INTEGER_LITERAL { $$ = new AnnotationConstant(toInteger($1), $1); } | BOOLEAN_LITERAL { $$ = new AnnotationConstant(toBoolean($1), $1); } | CHAR_LITERAL { String s = lexer.getCodeBody(); $$ = new AnnotationConstant(toChar(s), s); } | STRING_LITERAL { String s = lexer.getCodeBody(); $$ = new AnnotationConstant(toString(s), s); }; primitiveType: BOOLEAN { $$ = "boolean"; } | BYTE { $$ = "byte"; } | SHORT { $$ = "short"; } | INT { $$ = "int"; } | LONG { $$ = "long"; } | CHAR { $$ = "char"; } | FLOAT { $$ = "float"; } | DOUBLE { $$ = "double"; }; // ----- TYPES type: classtype dimensions { TypeDef td = $1; td.dimensions = $2; $$ = td; }; classtype: typedeclspecifier LESSTHAN { TypeDef td = new TypeDef($1,0); td.actualArgumentTypes = new ArrayList(); $$ = (TypeDef) typeStack.push(td); } typearglist { $$ = (TypeDef) typeStack.pop(); } GREATERTHAN { $$ = $5; } | typedeclspecifier { $$ = new TypeDef($1,0); }; typedeclspecifier: typename { $$ = $1; } | classtype DOT IDENTIFIER { $$ = $1.name + '.' + $3; }; typename: IDENTIFIER { $$ = $1; } | typename DOT IDENTIFIER { $$ = $1 + '.' + $3; }; typearglist: typearg { ((TypeDef) typeStack.peek()).actualArgumentTypes.add($1);}| typearglist COMMA typearg { ((TypeDef) typeStack.peek()).actualArgumentTypes.add($3);}; typearg: type { $$ = $1;} | QUERY { $$ = new WildcardTypeDef();} | QUERY EXTENDS type { $$ = new WildcardTypeDef($3, "extends");} | QUERY SUPER type { $$ = new WildcardTypeDef($3, "super");}; opt_typeparams: | typeparams; typeparams: LESSTHAN { typeParams = new ArrayList(); } typeparamlist GREATERTHAN; typeparamlist: typeparam | typeparamlist COMMA typeparam; typeparam: IDENTIFIER { typeParams.add(new TypeVariableDef($1)); } | IDENTIFIER EXTENDS { typeVariable = new TypeVariableDef($1); typeVariable.bounds = new ArrayList(); } typeboundlist { typeParams.add(typeVariable); typeVariable = null; }; typeboundlist: type { typeVariable.bounds.add($1); } | typeboundlist AMPERSAND type { typeVariable.bounds.add($3); }; // ----- ENUM enum: enum_definition BRACEOPEN enum_body BRACECLOSE { builder.endClass(); fieldType = null; modifiers.clear(); }; enum_definition: modifiers ENUM IDENTIFIER opt_implements { cls.lineNumber = line; cls.modifiers.addAll(modifiers); cls.name = $3; cls.type = ClassDef.ENUM; builder.beginClass(cls); cls = new ClassDef(); fieldType = new TypeDef($3, 0); }; enum_body: enum_values | enum_values SEMI members; enum_values: | enum_value | enum_value COMMA enum_values; enum_value: javadoclist opt_annotations enum_constructor | opt_annotations enum_constructor; enum_constructor: IDENTIFIER { makeField(new TypeDef($1, 0), ""); } | IDENTIFIER CODEBLOCK { makeField(new TypeDef($1, 0), ""); } | IDENTIFIER PARENBLOCK { makeField(new TypeDef($1, 0), ""); } | IDENTIFIER PARENBLOCK CODEBLOCK { makeField(new TypeDef($1, 0), ""); }; // ----- CLASS class: classdefinition BRACEOPEN members BRACECLOSE { builder.endClass(); }; classdefinition: modifiers classorinterface IDENTIFIER opt_typeparams opt_extends opt_implements { cls.lineNumber = line; cls.modifiers.addAll(modifiers); modifiers.clear(); cls.name = $3; cls.typeParams = typeParams; builder.beginClass(cls); cls = new ClassDef(); }; classorinterface: CLASS { cls.type = ClassDef.CLASS; } | INTERFACE { cls.type = ClassDef.INTERFACE; } | ANNOINTERFACE { cls.type = ClassDef.ANNOTATION_TYPE; }; opt_extends: | EXTENDS extendslist; extendslist: classtype { cls.extendz.add($1); } | extendslist COMMA classtype { cls.extendz.add($3); }; opt_implements: | IMPLEMENTS implementslist; implementslist: classtype { cls.implementz.add($1); } | implementslist COMMA classtype { cls.implementz.add($3); }; members: | members { line = lexer.getLine(); } member; member: javadoc | fields | method | constructor | static_block | class | enum | SEMI; memberend: SEMI { $$ = ""; } | CODEBLOCK { $$ = lexer.getCodeBody(); }; static_block: modifiers CODEBLOCK { lexer.getCodeBody(); modifiers.clear(); }; // ----- FIELD fields: modifiers type arrayidentifier { fieldType = $2; makeField($3, lexer.getCodeBody()); } extrafields memberend { modifiers.clear(); }; extrafields: | extrafields COMMA { line = lexer.getLine(); } arrayidentifier { makeField($4, lexer.getCodeBody()); } | extrafields COMMA javadoc { line = lexer.getLine(); } arrayidentifier { makeField($5, lexer.getCodeBody()); }; // ----- METHOD method: modifiers typeparams type IDENTIFIER { builder.beginMethod(); mth.typeParams = typeParams; } methoddef dimensions opt_exceptions memberend { mth.lineNumber = line; mth.modifiers.addAll(modifiers); modifiers.clear(); mth.returnType = $3; mth.dimensions = $7; mth.name = $4; mth.body = $9; builder.endMethod(mth); mth = new MethodDef(); } | modifiers type IDENTIFIER { builder.beginMethod(); } methoddef dimensions opt_exceptions memberend { mth.lineNumber = line; mth.modifiers.addAll(modifiers); modifiers.clear(); mth.returnType = $2; mth.dimensions = $6; mth.name = $3; mth.body = $8; builder.endMethod(mth); mth = new MethodDef(); }; constructor: modifiers IDENTIFIER { builder.beginMethod(); } methoddef opt_exceptions memberend { mth.lineNumber = line; mth.modifiers.addAll(modifiers); modifiers.clear(); mth.constructor = true; mth.name = $2; mth.body = $6; builder.endMethod(mth); mth = new MethodDef(); } | modifiers typeparams IDENTIFIER { builder.beginMethod(); mth.typeParams = typeParams; } methoddef opt_exceptions memberend { mth.lineNumber = line; mth.modifiers.addAll(modifiers); modifiers.clear(); mth.constructor = true; mth.name = $3; mth.body = $7; builder.endMethod(mth); mth = new MethodDef(); }; methoddef: PARENOPEN opt_params PARENCLOSE; opt_exceptions: | THROWS exceptionlist; exceptionlist: fullidentifier { mth.exceptions.add($1); } | exceptionlist COMMA fullidentifier { mth.exceptions.add($3); }; opt_params: | paramlist; paramlist: param | paramlist COMMA param; param: opt_parammodifiers type varargs arrayidentifier { param.name = $4.name; param.type = $2; param.dimensions = $4.dimensions; param.isVarArgs = $3; builder.addParameter(param); param = new FieldDef(); }; varargs: /* empty */ { $$ = false; } | DOTDOTDOT { $$ = true; } ; opt_annotations: | opt_annotations annotation { builder.addAnnotation((Annotation) $2); }; opt_parammodifiers: | opt_parammodifiers modifier { param.modifiers.add($2); } | opt_parammodifiers annotation { builder.addAnnotation((Annotation) $2); }; %% private Lexer lexer; private Builder builder; private StringBuffer textBuffer = new StringBuffer(); private ClassDef cls = new ClassDef(); private MethodDef mth = new MethodDef(); private List typeParams = new ArrayList(); //for both JavaClass and JavaMethod private List annotationStack = new ArrayList(); // Use ArrayList intead of Stack because it is unsynchronized private Annotation annotation = null; private List annoValueListStack = new ArrayList(); // Use ArrayList intead of Stack because it is unsynchronized private List annoValueList = null; private FieldDef param = new FieldDef(); private java.util.Set modifiers = new java.util.HashSet(); private TypeDef fieldType; private TypeVariableDef typeVariable; private Stack typeStack = new Stack(); private int line; private int column; private boolean debugLexer; private void appendToBuffer(String word) { if (textBuffer.length() > 0) { char lastChar = textBuffer.charAt(textBuffer.length() - 1); if (!Character.isWhitespace(lastChar)) { textBuffer.append(' '); } } textBuffer.append(word); } private String buffer() { String result = textBuffer.toString().trim(); textBuffer.setLength(0); return result; } public Parser(Lexer lexer, Builder builder) { this.lexer = lexer; this.builder = builder; } public void setDebugParser(boolean debug) { yydebug = debug; } public void setDebugLexer(boolean debug) { debugLexer = debug; } /** * Parse file. Return true if successful. */ public boolean parse() { return yyparse() == 0; } private int yylex() { try { final int result = lexer.lex(); yylval = new Value(); yylval.sval = lexer.text(); if (debugLexer) { System.err.println("Token: " + yyname[result] + " \"" + yylval.sval + "\""); } return result; } catch(IOException e) { return 0; } } private void yyerror(String msg) { throw new ParseException(msg, lexer.getLine(), lexer.getColumn()); } private class Value { Object oval; String sval; int ival; boolean bval; TypeDef type; AnnotationValue annoval; } private void makeField(TypeDef field, String body) { FieldDef fd = new FieldDef(); fd.lineNumber = line; fd.modifiers.addAll(modifiers); fd.name = field.name; fd.type = fieldType; fd.dimensions = field.dimensions; fd.body = body; builder.addField(fd); } private String convertString(String str) { StringBuffer buf = new StringBuffer(); boolean escaped = false; int unicode = 0; int value = 0; int octal = 0; boolean consumed = false; for(int i = 0; i < str.length(); ++ i) { char ch = str.charAt( i ); if(octal > 0) { if( value >= '0' && value <= '7' ) { value = ( value << 3 ) | Character.digit( ch, 8 ); -- octal; consumed = true; } else { octal = 0; } if( octal == 0 ) { buf.append( (char) value ); value = 0; } } if(!consumed) { if(unicode > 0) { value = ( value << 4 ) | Character.digit( ch, 16 ); -- unicode; if(unicode == 0) { buf.append( (char)value ); value = 0; } } else if(escaped) { if(ch == 'u' || ch == 'U') { unicode = 4; } else if(ch >= '0' && ch <= '7') { octal = (ch > '3') ? 1 : 2; value = Character.digit( ch, 8 ); } else { switch( ch ) { case 'b': buf.append('\b'); break; case 'f': buf.append('\f'); break; case 'n': buf.append('\n'); break; case 'r': buf.append('\r'); break; case 't': buf.append('\t'); break; case '\'': buf.append('\''); break; case '\"': buf.append('\"'); break; case '\\': buf.append('\\'); break; default: yyerror( "Illegal escape character '" + ch + "'" ); } } escaped = false; } else if(ch == '\\') { escaped = true; } else { buf.append( ch ); } } } return buf.toString(); } private Boolean toBoolean(String str) { str = str.trim(); return new Boolean( str ); } private Integer toInteger(String str) { str = str.trim(); Integer result; if(str.startsWith("0x") || str.startsWith( "0X" ) ) { result = new Integer( Integer.parseInt( str.substring( 2 ), 16 ) ); } else if(str.length() > 1 && str.startsWith("0") ) { result = new Integer( Integer.parseInt( str.substring( 1 ), 8 ) ); } else { result = new Integer( str ); } return result; } private Long toLong(String str) { str = str.trim(); Long result; if( !str.endsWith("l") && !str.endsWith("L") ) { yyerror( "Long literal must end with 'l' or 'L'." ); } int len = str.length() - 1; if(str.startsWith("0x") || str.startsWith( "0X" ) ) { result = new Long( Long.parseLong( str.substring( 2, len ), 16 ) ); } else if(str.startsWith("0") ) { result = new Long( Long.parseLong( str.substring( 1, len ), 8 ) ); } else { result = new Long( str.substring( 0, len ) ); } return result; } private Float toFloat(String str) { str = str.trim(); return new Float( str ); } private Double toDouble(String str) { str = str.trim(); if( !str.endsWith("d") && !str.endsWith("D") ) { yyerror( "Double literal must end with 'd' or 'D'." ); } return new Double( str.substring( 0, str.length() - 1 ) ); } /** * Convert a character literal into a character. */ private Character toChar(String str) { str = str.trim(); if( !str.startsWith("'") && !str.endsWith("'") ) { yyerror("Character must be single quoted."); } String str2 = convertString( str.substring( 1, str.length() - 1 ) ); if( str2.length() != 1) { yyerror("Only one character allowed in character constants."); } return new Character( str2.charAt( 0 ) ); } /** * Convert a string literal into a string. */ private String toString(String str) { str = str.trim(); if( str.length() < 2 && !str.startsWith("\"") && !str.endsWith("\"") ) { yyerror("String must be double quoted."); } String str2 = convertString( str.substring( 1, str.length() - 1 ) ); return str2; }qdox-qdox-1.12.1/src/grammar/skeleton.inner000066400000000000000000000255221204551233600206250ustar00rootroot00000000000000/* This file is based on skeleton.nested, but this version skips resetting the line number and column. It's used for parsing the javadoc comments. It's much more solid to extract the comment block and read it per line. */ /** This character denotes the end of file */ public static final int YYEOF = -1; /** initial size of the lookahead buffer */ --- private static final int ZZ_BUFFERSIZE = ...; /** lexical states */ --- lexical states, charmap /* error codes */ private static final int ZZ_UNKNOWN_ERROR = 0; private static final int ZZ_NO_MATCH = 1; private static final int ZZ_PUSHBACK_2BIG = 2; /* error messages for the codes above */ private static final String ZZ_ERROR_MSG[] = { "Unkown internal scanner error", "Error: could not match input", "Error: pushback value was too large" }; --- isFinal list /** the input device */ private java.io.Reader zzReader; /** the current state of the DFA */ private int zzState; /** the current lexical state */ private int zzLexicalState = YYINITIAL; /** this buffer contains the current text to be matched and is the source of the yytext() string */ private char zzBuffer[] = new char[ZZ_BUFFERSIZE]; /** the textposition at the last accepting state */ private int zzMarkedPos; /** the current text position in the buffer */ private int zzCurrentPos; /** startRead marks the beginning of the yytext() string in the buffer */ private int zzStartRead; /** endRead marks the last character in the buffer, that has been read from input */ private int zzEndRead; /** number of newlines encountered up to the start of the matched text */ private int yyline; /** the number of characters up to the start of the matched text */ private int yychar; /** * the number of characters from the last newline up to the start of the * matched text */ private int yycolumn; /** * zzAtBOL == true <=> the scanner is currently at the beginning of a line */ private boolean zzAtBOL = true; /** zzAtEOF == true <=> the scanner is at the EOF */ private boolean zzAtEOF; /** denotes if the user-EOF-code has already been executed */ private boolean zzEOFDone; /** the stack of open (nested) input streams to read from */ private java.util.Stack zzStreams = new java.util.Stack(); /** * inner class used to store info for nested * input streams */ private static final class ZzFlexStreamInfo { java.io.Reader zzReader; int zzEndRead; int zzStartRead; int zzCurrentPos; int zzMarkedPos; char [] zzBuffer; boolean zzAtEOF; boolean zzEOFDone; /** sets all values stored in this class */ ZzFlexStreamInfo(java.io.Reader zzReader, int zzEndRead, int zzStartRead, int zzCurrentPos, int zzMarkedPos, char [] zzBuffer, boolean zzAtEOF) { this.zzReader = zzReader; this.zzEndRead = zzEndRead; this.zzStartRead = zzStartRead; this.zzCurrentPos = zzCurrentPos; this.zzMarkedPos = zzMarkedPos; this.zzBuffer = zzBuffer; this.zzAtEOF = zzAtEOF; this.zzEOFDone = zzEOFDone; } } --- user class code /** * Creates a new scanner * There is also a java.io.InputStream version of this constructor. * * @param in the java.io.Reader to read input from. */ --- constructor declaration /** * Refills the input buffer. * * @return false, iff there was new input. * * @exception java.io.IOException if any I/O-Error occurs */ private boolean zzRefill() throws java.io.IOException { /* first: make room (if you can) */ if (zzStartRead > 0) { System.arraycopy(zzBuffer, zzStartRead, zzBuffer, 0, zzEndRead-zzStartRead); /* translate stored positions */ zzEndRead-= zzStartRead; zzCurrentPos-= zzStartRead; zzMarkedPos-= zzStartRead; zzStartRead = 0; } /* is the buffer big enough? */ if (zzCurrentPos >= zzBuffer.length) { /* if not: blow it up */ char newBuffer[] = new char[zzCurrentPos*2]; System.arraycopy(zzBuffer, 0, newBuffer, 0, zzBuffer.length); zzBuffer = newBuffer; } /* finally: fill the buffer with new input */ int numRead = zzReader.read(zzBuffer, zzEndRead, zzBuffer.length-zzEndRead); if (numRead > 0) { zzEndRead+= numRead; return false; } // unlikely but not impossible: read 0 characters, but not at end of stream if (numRead == 0) { int c = zzReader.read(); if (c == -1) { return true; } else { zzBuffer[zzEndRead++] = (char) c; return false; } } // numRead < 0) return true; } /** * Closes the input stream. */ public final void yyclose() throws java.io.IOException { zzAtEOF = true; /* indicate end of file */ zzEndRead = zzStartRead; /* invalidate buffer */ if (zzReader != null) zzReader.close(); } /** * Stores the current input stream on a stack, and * reads from a new stream. Lexical state, line, * char, and column counting remain untouched. * * The current input stream can be restored with * yypopstream (usually in an <> action). * * @param reader the new input stream to read from * * @see #yypopStream() */ public final void yypushStream(java.io.Reader reader) { zzStreams.push( new ZzFlexStreamInfo(zzReader, zzEndRead, zzStartRead, zzCurrentPos, zzMarkedPos, zzBuffer, zzAtEOF) ); zzAtEOF = false; zzBuffer = new char[ZZ_BUFFERSIZE]; zzReader = reader; zzEndRead = zzStartRead = 0; zzCurrentPos = zzMarkedPos = 0; } /** * Closes the current input stream and continues to * read from the one on top of the stream stack. * * @throws java.util.EmptyStackException * if there is no further stream to read from. * * @throws java.io.IOException * if there was an error in closing the stream. * * @see #yypushStream(java.io.Reader) */ public final void yypopStream() throws java.io.IOException { zzReader.close(); ZzFlexStreamInfo s = (ZzFlexStreamInfo) zzStreams.pop(); zzBuffer = s.zzBuffer; zzReader = s.zzReader; zzStartRead = s.zzStartRead + zzEndRead + 2; //skip javadoc-part zzEndRead = s.zzEndRead; zzCurrentPos = s.zzCurrentPos; zzMarkedPos = s.zzMarkedPos ; zzAtEOF = s.zzAtEOF; zzEOFDone = s.zzEOFDone; } /** * Returns true iff there are still streams left * to read from on the stream stack. */ public final boolean yymoreStreams() { return !zzStreams.isEmpty(); } /** * Resets the scanner to read from a new input stream. * Does not close the old reader. * * All internal variables are reset, the old input stream * cannot be reused (internal buffer is discarded and lost). * Lexical state is set to ZZ_INITIAL. * * @param reader the new input stream * * @see #yypushStream(java.io.Reader) * @see #yypopStream() */ public final void yyreset(java.io.Reader reader) { zzReader = reader; zzAtBOL = true; zzAtEOF = false; zzEOFDone = false; zzEndRead = zzStartRead = 0; zzCurrentPos = zzMarkedPos = 0; yychar = 0; zzLexicalState = YYINITIAL; } /** * Returns the current lexical state. */ public final int yystate() { return zzLexicalState; } /** * Enters a new lexical state * * @param newState the new lexical state */ public final void yybegin(int newState) { zzLexicalState = newState; } /** * Returns the text matched by the current regular expression. */ public final String yytext() { return new String( zzBuffer, zzStartRead, zzMarkedPos-zzStartRead ); } /** * Returns the character at position pos from the * matched text. * * It is equivalent to yytext().charAt(pos), but faster * * @param pos the position of the character to fetch. * A value from 0 to yylength()-1. * * @return the character at position pos */ public final char yycharat(int pos) { return zzBuffer[zzStartRead+pos]; } /** * Returns the length of the matched text region. */ public final int yylength() { return zzMarkedPos-zzStartRead; } /** * Reports an error that occured while scanning. * * In a wellformed scanner (no or only correct usage of * yypushback(int) and a match-all fallback rule) this method * will only be called with things that "Can't Possibly Happen". * If this method is called, something is seriously wrong * (e.g. a JFlex bug producing a faulty scanner etc.). * * Usual syntax/scanner level error handling should be done * in error fallback rules. * * @param errorCode the code of the errormessage to display */ --- zzScanError declaration String message; try { message = ZZ_ERROR_MSG[errorCode]; } catch (ArrayIndexOutOfBoundsException e) { message = ZZ_ERROR_MSG[ZZ_UNKNOWN_ERROR]; } --- throws clause } /** * Pushes the specified amount of characters back into the input stream. * * They will be read again by then next call of the scanning method * * @param number the number of characters to be read again. * This number must not be greater than yylength()! */ --- yypushback decl (contains zzScanError exception) if ( number > yylength() ) zzScanError(ZZ_PUSHBACK_2BIG); zzMarkedPos -= number; } --- zzDoEOF /** * Resumes scanning until the next regular expression is matched, * the end of input is encountered or an I/O-Error occurs. * * @return the next token * @exception java.io.IOException if any I/O-Error occurs */ --- yylex declaration int zzInput; int zzAction; --- local declarations while (true) { // cached fields: int zzCurrentPosL; int zzMarkedPosL = zzMarkedPos; int zzEndReadL = zzEndRead; char [] zzBufferL = zzBuffer; char [] zzCMapL = ZZ_CMAP; --- start admin (line, char, col count) zzAction = -1; zzCurrentPosL = zzCurrentPos = zzStartRead = zzMarkedPosL; --- start admin (lexstate etc) zzForAction: { while (true) { --- next input, line, col, char count, next transition, isFinal action zzAction = zzState; zzMarkedPosL = zzCurrentPosL; --- line count update } } } // store back cached position zzMarkedPos = zzMarkedPosL; --- char count update --- actions default: if (zzInput == YYEOF && zzStartRead == zzCurrentPos) { zzAtEOF = true; --- eofvalue } else { --- no match } } } } --- main } qdox-qdox-1.12.1/src/java/000077500000000000000000000000001204551233600152315ustar00rootroot00000000000000qdox-qdox-1.12.1/src/java/com/000077500000000000000000000000001204551233600160075ustar00rootroot00000000000000qdox-qdox-1.12.1/src/java/com/thoughtworks/000077500000000000000000000000001204551233600205575ustar00rootroot00000000000000qdox-qdox-1.12.1/src/java/com/thoughtworks/qdox/000077500000000000000000000000001204551233600215325ustar00rootroot00000000000000qdox-qdox-1.12.1/src/java/com/thoughtworks/qdox/DefaultJavaClassCache.java000066400000000000000000000011441204551233600264750ustar00rootroot00000000000000package com.thoughtworks.qdox; import java.util.Hashtable; import java.util.Map; import com.thoughtworks.qdox.model.JavaClass; import com.thoughtworks.qdox.model.JavaClassCache; public class DefaultJavaClassCache implements JavaClassCache { private Map classes = new Hashtable(); public JavaClass getClassByName(String name) { return (JavaClass) classes.get(name); } public JavaClass[] getClasses() { return (JavaClass[]) classes.values().toArray(new JavaClass[0]); } public void putClassByName(String name, JavaClass javaClass) { classes.put(name, javaClass); } } qdox-qdox-1.12.1/src/java/com/thoughtworks/qdox/JavaClassContext.java000066400000000000000000000060761204551233600256220ustar00rootroot00000000000000package com.thoughtworks.qdox; import java.io.Serializable; import java.util.HashMap; import java.util.Map; import com.thoughtworks.qdox.model.ClassLibrary; import com.thoughtworks.qdox.model.JavaClass; import com.thoughtworks.qdox.model.JavaClassCache; import com.thoughtworks.qdox.model.JavaPackage; /** * JavaClassContext gives you a mechanism to get a JavaClass. * If a class couldn't be found in the cache, the class will be pulled from the classLibrary, the builder will create the corresponding JavaClass and put it in the cache. * * * @author Robert Scholte * */ public class JavaClassContext implements Serializable { private final JavaClassCache cache; private ClassLibrary classLibrary; private JavaDocBuilder builder; private Map packageMap = new HashMap(); // public JavaClassContext(JavaDocBuilder builder) { this.builder = builder; this.cache = new DefaultJavaClassCache(); } public JavaClassContext(ClassLibrary classLibrary) { this.classLibrary = classLibrary; this.cache = new DefaultJavaClassCache(); } public void setClassLibrary(ClassLibrary classLibrary) { this.classLibrary = classLibrary; } /** * temporary, this should be hidden * @return classLibrary * @todo remove */ public ClassLibrary getClassLibrary() { return classLibrary; } public JavaClass getClassByName(String name) { JavaClass result = cache.getClassByName(name); if(result == null && builder != null) { result = builder.createBinaryClass(name); if ( result == null ) { result = builder.createSourceClass(name); } if ( result == null ) { result = builder.createUnknownClass(name); } if(result != null) { add(result); result.setJavaClassContext(this); } } return result; } public JavaClass[] getClasses() { return cache.getClasses(); } public void add(JavaClass javaClass) { cache.putClassByName(javaClass.getFullyQualifiedName(), javaClass); JavaPackage jPackage = getPackageByName( javaClass.getPackageName() ); if(jPackage != null) { jPackage.addClass( javaClass ); } } public void add(String fullyQualifiedClassName) { classLibrary.add(fullyQualifiedClassName); } public Class getClass(String name) { return classLibrary.getClass(name); } public JavaPackage getPackageByName( String name ) { return (JavaPackage) packageMap.get( name ); } public void add( JavaPackage jPackage ) { String packageName = jPackage.getName(); JavaPackage javaPackage = getPackageByName( packageName ); if ( javaPackage == null ) { javaPackage = new JavaPackage( packageName ); javaPackage.setContext( this ); packageMap.put( packageName, javaPackage ); } jPackage.setContext( this ); } public JavaPackage[] getPackages() { return (JavaPackage[]) packageMap.values().toArray( new JavaPackage[0] ); } } qdox-qdox-1.12.1/src/java/com/thoughtworks/qdox/JavaDocBuilder.java000066400000000000000000000452241204551233600252220ustar00rootroot00000000000000package com.thoughtworks.qdox; import com.thoughtworks.qdox.directorywalker.DirectoryScanner; import com.thoughtworks.qdox.directorywalker.FileVisitor; import com.thoughtworks.qdox.directorywalker.SuffixFilter; import com.thoughtworks.qdox.model.ClassLibrary; import com.thoughtworks.qdox.model.DefaultDocletTagFactory; import com.thoughtworks.qdox.model.DocletTagFactory; import com.thoughtworks.qdox.model.JavaClass; import com.thoughtworks.qdox.model.JavaClassCache; import com.thoughtworks.qdox.model.JavaSource; import com.thoughtworks.qdox.model.ModelBuilder; import com.thoughtworks.qdox.model.JavaPackage; import com.thoughtworks.qdox.parser.Lexer; import com.thoughtworks.qdox.parser.ParseException; import com.thoughtworks.qdox.parser.impl.JFlexLexer; import com.thoughtworks.qdox.parser.impl.Parser; import com.thoughtworks.qdox.parser.structs.ClassDef; import com.thoughtworks.qdox.parser.structs.FieldDef; import com.thoughtworks.qdox.parser.structs.MethodDef; import com.thoughtworks.qdox.parser.structs.PackageDef; import com.thoughtworks.qdox.parser.structs.TypeDef; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Reader; import java.io.Serializable; import java.io.UnsupportedEncodingException; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Member; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.StringTokenizer; /** * Simple facade to QDox allowing a source tree to be parsed and the resulting object model navigated. * *

Example

*

 * // -- Create JavaDocBuilder
 *
 * JavaDocBuilder builder = new JavaDocBuilder();
 *
 * // -- Add some files
 *
 * // Reading a single source file.
 * builder.addSource(new FileReader("MyFile.java"));
 *
 * // Reading from another kind of input stream.
 * builder.addSource(new StringReader("package test; public class Hello {}"));
 *
 * // Adding all .java files in a source tree (recursively).
 * builder.addSourceTree(new File("mysrcdir"));
 *
 * // -- Retrieve source files
 *
 * JavaSource[] source = builder.getSources();
 *
 * 
* * @author Joe Walnes * @author Aslak Hellesøy * @author Robert Scholte */ public class JavaDocBuilder implements Serializable { private final JavaClassContext context; private Set packages = new HashSet(); private List sources = new ArrayList(); private DocletTagFactory docletTagFactory; private String encoding = System.getProperty("file.encoding"); private boolean debugLexer; private boolean debugParser; private ErrorHandler errorHandler = new DefaultErrorHandler(); public static interface ErrorHandler { void handle(ParseException parseException); } public static class DefaultErrorHandler implements ErrorHandler, Serializable { public void handle(ParseException parseException) { throw parseException; } } public JavaDocBuilder() { this(new DefaultDocletTagFactory()); } public JavaDocBuilder(DocletTagFactory docletTagFactory) { this.docletTagFactory = docletTagFactory; ClassLibrary classLibrary = new ClassLibrary(); classLibrary.addDefaultLoader(); this.context = new JavaClassContext(this); this.context.setClassLibrary(classLibrary); } public JavaDocBuilder(ClassLibrary classLibrary) { this(new DefaultDocletTagFactory(), classLibrary); } public JavaDocBuilder(DocletTagFactory docletTagFactory, ClassLibrary classLibrary) { this.docletTagFactory = docletTagFactory; this.context = new JavaClassContext(this); this.context.setClassLibrary(classLibrary); } private void addClasses(JavaSource source) { Set resultSet = new HashSet(); addClassesRecursive(source, resultSet); JavaClass[] javaClasses = (JavaClass[]) resultSet.toArray(new JavaClass[resultSet.size()]); for (int classIndex = 0; classIndex < javaClasses.length; classIndex++) { JavaClass cls = javaClasses[classIndex]; addClass(cls); } } private void addClass(JavaClass cls) { context.add(cls); cls.setJavaClassContext(context); } public JavaClass getClassByName(String name) { if (name == null) { return null; } return context.getClassByName(name); } protected JavaClass createSourceClass(String name) { File sourceFile = context.getClassLibrary().getSourceFile( name ); if (sourceFile != null) { try { JavaSource source = addSource( sourceFile ); for (int index = 0; index < source.getClasses().length; index++) { JavaClass clazz = source.getClasses()[index]; if (name.equals(clazz.getFullyQualifiedName())) { return clazz; } } return source.getNestedClassByName( name ); } catch ( FileNotFoundException e ) { //nop } catch ( IOException e ) { //nop } } return null; } protected JavaClass createUnknownClass(String name) { ModelBuilder unknownBuilder = new ModelBuilder(context, docletTagFactory, new HashMap()); ClassDef classDef = new ClassDef(); classDef.name = name; unknownBuilder.beginClass(classDef); unknownBuilder.endClass(); JavaSource unknownSource = unknownBuilder.getSource(); JavaClass result = unknownSource.getClasses()[0]; return result; } protected JavaClass createBinaryClass(String name) { // First see if the class exists at all. Class clazz = context.getClass(name); if (clazz == null) { return null; } else { try { // Create a new builder and mimic the behaviour of the parser. // We're getting all the information we need via reflection instead. ModelBuilder binaryBuilder = new ModelBuilder(context, docletTagFactory, new HashMap()); // Set the package name and class name String packageName = getPackageName(name); binaryBuilder.addPackage(new PackageDef(packageName)); ClassDef classDef = new ClassDef(); classDef.name = getClassName(name); // Set the extended class and interfaces. Class[] interfaces = clazz.getInterfaces(); if (clazz.isInterface()) { // It's an interface classDef.type = ClassDef.INTERFACE; for (int i = 0; i < interfaces.length; i++) { Class anInterface = interfaces[i]; classDef.extendz.add(new TypeDef(anInterface.getName())); } } else { // It's a class for (int i = 0; i < interfaces.length; i++) { Class anInterface = interfaces[i]; classDef.implementz.add(new TypeDef(anInterface.getName())); } Class superclass = clazz.getSuperclass(); if (superclass != null) { classDef.extendz.add(new TypeDef(superclass.getName())); } } addModifiers(classDef.modifiers, clazz.getModifiers()); binaryBuilder.beginClass(classDef); // add the constructors // // This also adds the default constructor if any which is different // to the source code as that does not create a default constructor // if no constructor exists. Constructor[] constructors = clazz.getDeclaredConstructors(); for (int i = 0; i < constructors.length; i++) { addMethodOrConstructor(constructors[i], binaryBuilder); } // add the methods Method[] methods = clazz.getDeclaredMethods(); for (int i = 0; i < methods.length; i++) { addMethodOrConstructor(methods[i], binaryBuilder); } Field[] fields = clazz.getDeclaredFields(); for (int i = 0; i < fields.length; i++) { addField(fields[i], binaryBuilder); } binaryBuilder.endClass(); JavaSource binarySource = binaryBuilder.getSource(); // There is always only one class in a "binary" source. JavaClass result = binarySource.getClasses()[0]; return result; } catch (NoClassDefFoundError e) { return null; } } } private void addModifiers(Set set, int modifier) { String modifierString = Modifier.toString(modifier); for (StringTokenizer stringTokenizer = new StringTokenizer(modifierString); stringTokenizer.hasMoreTokens();) { set.add(stringTokenizer.nextToken()); } } private void addField(Field field, ModelBuilder binaryBuilder) { FieldDef fieldDef = new FieldDef(); Class fieldType = field.getType(); fieldDef.name = field.getName(); fieldDef.type = getTypeDef(fieldType); fieldDef.dimensions = getDimension(fieldType); addModifiers( fieldDef.modifiers, field.getModifiers()); binaryBuilder.addField(fieldDef); } private void addMethodOrConstructor(Member member, ModelBuilder binaryBuilder) { MethodDef methodDef = new MethodDef(); // The name of constructors are qualified. Need to strip it. // This will work for regular methods too, since -1 + 1 = 0 int lastDot = member.getName().lastIndexOf('.'); methodDef.name = member.getName().substring(lastDot + 1); addModifiers(methodDef.modifiers, member.getModifiers()); Class[] exceptions; Class[] parameterTypes; if (member instanceof Method) { methodDef.constructor = false; // For some stupid reason, these methods are not defined in Member, // but in both Method and Construcotr. exceptions = ((Method) member).getExceptionTypes(); parameterTypes = ((Method) member).getParameterTypes(); Class returnType = ((Method) member).getReturnType(); methodDef.returnType = getTypeDef(returnType); methodDef.dimensions = getDimension(returnType); } else { methodDef.constructor = true; exceptions = ((Constructor) member).getExceptionTypes(); parameterTypes = ((Constructor) member).getParameterTypes(); } for (int j = 0; j < exceptions.length; j++) { Class exception = exceptions[j]; methodDef.exceptions.add(exception.getName()); } binaryBuilder.addMethod(methodDef); for (int j = 0; j < parameterTypes.length; j++) { FieldDef param = new FieldDef(); Class parameterType = parameterTypes[j]; param.name = "p" + j; param.type = getTypeDef(parameterType); param.dimensions = getDimension(parameterType); binaryBuilder.addParameter( param ); } } private static final int getDimension(Class c) { return c.getName().lastIndexOf('[') + 1; } private static String getTypeName(Class c) { return c.getComponentType() != null ? c.getComponentType().getName() : c.getName(); } private static TypeDef getTypeDef(Class c) { return new TypeDef(getTypeName(c)); } private String getPackageName(String fullClassName) { int lastDot = fullClassName.lastIndexOf('.'); return lastDot == -1 ? "" : fullClassName.substring(0, lastDot); } private String getClassName(String fullClassName) { int lastDot = fullClassName.lastIndexOf('.'); return lastDot == -1 ? fullClassName : fullClassName.substring(lastDot + 1); } public JavaSource addSource(Reader reader) { return addSource(reader, "UNKNOWN SOURCE"); } public JavaSource addSource(Reader reader, String sourceInfo) { ModelBuilder builder = new ModelBuilder(context, docletTagFactory, null); Lexer lexer = new JFlexLexer(reader); Parser parser = new Parser(lexer, builder); parser.setDebugLexer(debugLexer); parser.setDebugParser(debugParser); try { parser.parse(); } catch (ParseException e) { e.setSourceInfo(sourceInfo); errorHandler.handle(e); } finally { try { reader.close(); } catch (IOException e) { } } JavaSource source = builder.getSource(); sources.add(source); addClasses(source); JavaPackage pkg = context.getPackageByName( source.getPackageName() ); if (!packages.contains(pkg)) { packages.add(pkg); } // JavaClass[] classes = source.getClasses(); // for (int i = 0; i < classes.length; i++) { // if (pkg != null) { // pkg.addClass(classes[i]); // } // } return source; } public JavaSource addSource(File file) throws IOException, FileNotFoundException { return addSource(file.toURL()); } public JavaSource addSource(URL url) throws IOException, FileNotFoundException { JavaSource source = addSource(new InputStreamReader(url.openStream(),encoding), url.toExternalForm()); source.setURL(url); return source; } public void setErrorHandler(ErrorHandler errorHandler) { this.errorHandler = errorHandler; } public JavaSource[] getSources() { return (JavaSource[]) sources.toArray(new JavaSource[sources.size()]); } /** * Returns all the classes found in all the sources, including inner classes * and "extra" classes (multiple outer classes defined in the same source file). * * @return all the classes found in all the sources. * @since 1.3 */ public JavaClass[] getClasses() { Set resultSet = new HashSet(); JavaSource[] javaSources = getSources(); for (int i = 0; i < javaSources.length; i++) { JavaSource javaSource = javaSources[i]; addClassesRecursive(javaSource, resultSet); } JavaClass[] result = (JavaClass[]) resultSet.toArray(new JavaClass[resultSet.size()]); return result; } /** * Returns all the packages found in all the sources. * * @return all the packages found in all the sources. * @since 1.9 */ public JavaPackage[] getPackages() { return (JavaPackage[]) packages.toArray(new JavaPackage[packages.size()]); } private void addClassesRecursive(JavaSource javaSource, Set resultSet) { JavaClass[] classes = javaSource.getClasses(); for (int j = 0; j < classes.length; j++) { JavaClass javaClass = classes[j]; addClassesRecursive(javaClass, resultSet); } } private void addClassesRecursive(JavaClass javaClass, Set set) { // Add the class... set.add(javaClass); // And recursively all of its inner classes JavaClass[] innerClasses = javaClass.getNestedClasses(); for (int i = 0; i < innerClasses.length; i++) { JavaClass innerClass = innerClasses[i]; addClassesRecursive(innerClass, set); } } /** * Add all files in a directory (and subdirs, recursively). * * If a file cannot be read, a RuntimeException shall be thrown. */ public void addSourceTree(File file) { FileVisitor errorHandler = new FileVisitor() { public void visitFile(File badFile) { throw new RuntimeException("Cannot read file : " + badFile.getName()); } }; addSourceTree(file, errorHandler); } /** * Add all files in a directory (and subdirs, recursively). * * If a file cannot be read, errorHandler will be notified. */ public void addSourceTree(File file, final FileVisitor errorHandler) { DirectoryScanner scanner = new DirectoryScanner(file); scanner.addFilter(new SuffixFilter(".java")); scanner.scan(new FileVisitor() { public void visitFile(File currentFile) { try { addSource(currentFile); } catch (IOException e) { errorHandler.visitFile(currentFile); } } }); } public List search(Searcher searcher) { List results = new LinkedList(); for (Iterator iterator = context.getClassLibrary().all().iterator(); iterator.hasNext();) { String clsName = (String) iterator.next(); JavaClass cls = getClassByName(clsName); if (searcher.eval(cls)) { results.add(cls); } } return results; } public ClassLibrary getClassLibrary() { return context.getClassLibrary(); } public void save(File file) throws IOException { FileOutputStream fos = new FileOutputStream(file); ObjectOutputStream out = new ObjectOutputStream(fos); try { out.writeObject(this); } finally { out.close(); fos.close(); } } /** * Note that after loading JavaDocBuilder classloaders need to be re-added. */ public static JavaDocBuilder load(File file) throws IOException { FileInputStream fis = new FileInputStream(file); ObjectInputStream in = new ObjectInputStream(fis); JavaDocBuilder builder = null; try { builder = (JavaDocBuilder) in.readObject(); } catch (ClassNotFoundException e) { throw new Error("Couldn't load class : " + e.getMessage()); } finally { in.close(); fis.close(); } return builder; } public void setEncoding(String encoding) { this.encoding = encoding; } /** * Forces QDox to dump tokens returned from lexer to System.err. */ public void setDebugLexer(boolean debugLexer) { this.debugLexer = debugLexer; } /** * Forces QDox to dump parser states to System.out. */ public void setDebugParser(boolean debugParser) { this.debugParser = debugParser; } public JavaPackage getPackageByName( String name ) { if(name != null) { Iterator iter = packages.iterator(); while(iter.hasNext()) { JavaPackage pkg = (JavaPackage) iter.next(); if(name.equals( pkg.getName() )) { return pkg; } } } return null; } } qdox-qdox-1.12.1/src/java/com/thoughtworks/qdox/Searcher.java000066400000000000000000000002201204551233600241230ustar00rootroot00000000000000package com.thoughtworks.qdox; import com.thoughtworks.qdox.model.JavaClass; public interface Searcher { boolean eval(JavaClass cls); } qdox-qdox-1.12.1/src/java/com/thoughtworks/qdox/ant/000077500000000000000000000000001204551233600223145ustar00rootroot00000000000000qdox-qdox-1.12.1/src/java/com/thoughtworks/qdox/ant/AbstractQdoxTask.java000066400000000000000000000060151204551233600264030ustar00rootroot00000000000000package com.thoughtworks.qdox.ant; import com.thoughtworks.qdox.JavaDocBuilder; import com.thoughtworks.qdox.model.JavaClass; import com.thoughtworks.qdox.model.JavaSource; import com.thoughtworks.qdox.model.DocletTagFactory; import com.thoughtworks.qdox.model.DefaultDocletTagFactory; import java.io.File; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.Vector; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.DirectoryScanner; import org.apache.tools.ant.Task; import org.apache.tools.ant.types.FileSet; public abstract class AbstractQdoxTask extends Task { private Vector filesets = new Vector(); protected HashMap fileMap = new HashMap(); protected ArrayList allSources = new ArrayList(); protected ArrayList allClasses = new ArrayList(); public void addFileset(FileSet set) { filesets.addElement(set); } protected void buildFileMap() { for (int i = 0; i < filesets.size(); i++) { FileSet fs = (FileSet) filesets.elementAt(i); DirectoryScanner ds = fs.getDirectoryScanner(getProject()); String[] srcFiles = ds.getIncludedFiles(); buildFileMap(fs.getDir(getProject()), srcFiles); } } protected void buildFileMap(File directory, String[] sourceFiles) { for (int i = 0; i < sourceFiles.length; i++) { File src = new File(directory, sourceFiles[i]); fileMap.put(src.getAbsolutePath(), src); } } public void execute() throws BuildException { validateAttributes(); buildFileMap(); JavaDocBuilder builder = new JavaDocBuilder(createDocletTagFactory()); // Add a classloader that has the taskdef's classpath. builder.getClassLibrary().addClassLoader(getClass().getClassLoader()); mergeBuilderSources(builder); JavaSource[] sources = builder.getSources(); processSources(sources); } protected DocletTagFactory createDocletTagFactory() { return new DefaultDocletTagFactory(); } private void mergeBuilderSources(JavaDocBuilder builder) { for (Iterator iterator = fileMap.keySet().iterator(); iterator.hasNext();) { String sourceFile = (String) iterator.next(); builder.addSourceTree((File) fileMap.get(sourceFile)); } } protected void processSources(JavaSource[] sources) { for (int i = 0; i < sources.length; i++) { JavaSource source = sources[i]; allSources.add(source); JavaClass[] classes = source.getClasses(); processClasses(classes); } } protected void processClasses(JavaClass[] classes) { for (int j = 0; j < classes.length; j++) { JavaClass clazz = classes[j]; allClasses.add(clazz); } } protected void validateAttributes() throws BuildException { if (filesets.size() == 0) { throw new BuildException("Specify at least one source fileset."); } } } qdox-qdox-1.12.1/src/java/com/thoughtworks/qdox/directorywalker/000077500000000000000000000000001204551233600247445ustar00rootroot00000000000000qdox-qdox-1.12.1/src/java/com/thoughtworks/qdox/directorywalker/DirectoryScanner.java000066400000000000000000000027501204551233600310710ustar00rootroot00000000000000package com.thoughtworks.qdox.directorywalker; import java.io.File; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.List; public class DirectoryScanner { private File file; private Collection filters = new HashSet(); public DirectoryScanner(File file) { this.file = file; } public File[] scan() { final List results = new ArrayList(); walk(new FileVisitor() { public void visitFile(File file) { results.add(file); } }, this.file); File[] resultsArray = new File[results.size()]; results.toArray(resultsArray); return resultsArray; } private void walk(FileVisitor visitor, File current) { if (current.isDirectory()) { File[] currentFiles = current.listFiles(); for (int i = 0; i < currentFiles.length; i++) { walk(visitor, currentFiles[i]); } } else { for (Iterator iterator = this.filters.iterator(); iterator.hasNext();) { Filter filter = (Filter) iterator.next(); if (!filter.filter(current)) { return; } } visitor.visitFile(current); } } public void addFilter(Filter filter) { this.filters.add(filter); } public void scan(FileVisitor fileVisitor) { walk(fileVisitor, this.file); } } qdox-qdox-1.12.1/src/java/com/thoughtworks/qdox/directorywalker/FileVisitor.java000066400000000000000000000002101204551233600300370ustar00rootroot00000000000000package com.thoughtworks.qdox.directorywalker; import java.io.File; public interface FileVisitor { void visitFile(File file); } qdox-qdox-1.12.1/src/java/com/thoughtworks/qdox/directorywalker/Filter.java000066400000000000000000000002031204551233600270270ustar00rootroot00000000000000package com.thoughtworks.qdox.directorywalker; import java.io.File; public interface Filter { boolean filter(File file); } qdox-qdox-1.12.1/src/java/com/thoughtworks/qdox/directorywalker/SuffixFilter.java000066400000000000000000000005401204551233600302200ustar00rootroot00000000000000package com.thoughtworks.qdox.directorywalker; import java.io.File; public class SuffixFilter implements Filter { private String suffixFilter; public SuffixFilter(String suffixFilter) { this.suffixFilter = suffixFilter; } public boolean filter(File file) { return file.getName().endsWith(this.suffixFilter); } } qdox-qdox-1.12.1/src/java/com/thoughtworks/qdox/junit/000077500000000000000000000000001204551233600226635ustar00rootroot00000000000000qdox-qdox-1.12.1/src/java/com/thoughtworks/qdox/junit/APITestCase.java000066400000000000000000000324771204551233600256100ustar00rootroot00000000000000package com.thoughtworks.qdox.junit; import com.thoughtworks.qdox.JavaDocBuilder; import com.thoughtworks.qdox.model.AbstractBaseJavaEntity; import com.thoughtworks.qdox.model.AbstractJavaEntity; import com.thoughtworks.qdox.model.JavaClass; import com.thoughtworks.qdox.model.JavaField; import com.thoughtworks.qdox.model.JavaSource; import junit.framework.TestCase; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.net.URL; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.StringTokenizer; /** * APITestCase is a JUnit extension that will let you compare two sources * (typically one kept as a static expected result and a generated one) on the API level. *

* This class has been ported from XJavaDoc's CodeTestCase, carrying over only the * parts that compare on the API level. The original CodeTestCase also has comparison * of Java source AST (Abstract Syntax Trees). This will probably be extracted into * a ASTTestCase class and hosted as a separate project somewhere else. It should * probably be based on JavaCC for ease of porting. * * @author Aslak Hellesøy * @author Laurent Etiemble */ public abstract class APITestCase extends TestCase { /* * Needed to sort JavaClass, JavaField and JavaMethod as they * don't implement Comparable */ private static Comparator ENTITY_COMPARATOR = new Comparator() { public int compare(Object o1, Object o2) { AbstractBaseJavaEntity entity1 = (AbstractBaseJavaEntity) o1; AbstractBaseJavaEntity entity2 = (AbstractBaseJavaEntity) o2; return entity1.getName().compareTo(entity2.getName()); } }; public APITestCase() { super(); } /** * Compares API of both sources in the readers. *

*

Note: This method is for backward naming compatiblity * with xjavadoc.codeunit.CodeTestCase.

* * @param expected the expected source * @param actual the actual source */ public static void assertApiEquals(URL expected, URL actual) throws IOException { JavaDocBuilder builder = new JavaDocBuilder(); builder.addSource(new InputStreamReader(expected.openStream()), expected.toExternalForm()); builder.addSource(new InputStreamReader(actual.openStream()), actual.toExternalForm()); JavaSource expectedSource = builder.getSources()[0]; JavaSource actualsource = builder.getSources()[1]; assertApiEquals(expectedSource, actualsource); } /** * Compares API of both JavaSource objects. * * @param expected the expected source * @param actual the actual source */ private static void assertApiEquals(JavaSource expected, JavaSource actual) { List expectedClasses = Arrays.asList(expected.getClasses()); Collections.sort(expectedClasses, ENTITY_COMPARATOR); List actualClasses = Arrays.asList(actual.getClasses()); Collections.sort(actualClasses, ENTITY_COMPARATOR); assertEquals("Number of classes should be equal", expectedClasses.size(), actualClasses.size()); for (int i = 0; i < expectedClasses.size(); i++) { assertClassesEqual((JavaClass) expectedClasses.get(i), (JavaClass) actualClasses.get(i)); } } /** * Compares an actual field to an expected one. *

*

As JavaClass doesn't not implements equals and * hashCode methods, the comparison is done by hand.

* * @param expected * @param actual */ private static void assertClassesEqual(JavaClass expected, JavaClass actual) { assertEquals("Package names should be equal", expected.getPackage(), actual.getPackage()); assertModifiersEquals("Class modifiers should be equal", expected, actual); assertEquals("Class names should be equal", expected.getName(), actual.getName()); if ((expected.getSuperJavaClass() != null) && (actual.getSuperJavaClass() != null)) { assertEquals("Super class should be equal", expected.getSuperJavaClass().getName(), actual.getSuperJavaClass().getName()); } if ((expected.getSuperJavaClass() == null) ^ (actual.getSuperJavaClass() == null)) { fail("Super class should be equal"); } assertInterfacesEqual(expected, actual); assertInnerClassesEquals(expected, actual); assertFieldsEqual(expected, actual); assertMethodsEqual(expected, actual); } /** * Compares an actual field to an expected one. *

*

As JavaField doesn't not implements equals and * hashCode methods, the comparison is done by hand.

* * @param expected * @param actual */ private static void assertFieldEquals(JavaField expected, JavaField actual) { StringBuffer message = new StringBuffer("-> assertFieldEquals"); message.append("\n\tExcepted : "); message.append(expected); message.append("\n\tActual : "); message.append(actual); message.append("\n"); assertEquals(message.toString() + "Field types should be equal", expected.getType(), actual.getType()); assertEquals(message.toString() + "Field names should be equal", expected.getName(), actual.getName()); assertModifiersEquals(message.toString() + "Field modifiers should be equal", expected, actual); } /** * Compares fields from an actual class to an expected one. *

*

The fields are sorted by name before comparison to be sure * that even if the fields are defined in a different order, the * comparison is still right.

*/ private static void assertFieldsEqual(JavaClass expected, JavaClass actual) { List expectedFields = Arrays.asList(expected.getFields()); Collections.sort(expectedFields, ENTITY_COMPARATOR); List actualFields = Arrays.asList(actual.getFields()); Collections.sort(actualFields, ENTITY_COMPARATOR); StringBuffer message = new StringBuffer("-> assertFieldsEqual"); message.append("\n\tExcepted : "); message.append(expectedFields); message.append("\n\tActual : "); message.append(actualFields); message.append("\n"); assertEquals(message.toString() + "Number of fields should be equal", expectedFields.size(), actualFields.size()); for (int i = 0; i < expectedFields.size(); i++) { assertFieldEquals((JavaField) expectedFields.get(i), (JavaField) actualFields.get(i)); } } /** * Compares inner classes from an actual class to an expected one. *

*

The inner classes are sorted by name before comparison to be sure * that even if the inner classes are defined in a different order, the * comparison is still right.

*/ private static void assertInnerClassesEquals(JavaClass expected, JavaClass actual) { List expectedInnerClasses = Arrays.asList(expected.getNestedClasses()); Collections.sort(expectedInnerClasses, ENTITY_COMPARATOR); List actualInnerClasses = Arrays.asList(actual.getNestedClasses()); Collections.sort(actualInnerClasses, ENTITY_COMPARATOR); StringBuffer message = new StringBuffer("-> assertInnerClassesEquals"); message.append("\n\tExcepted : "); message.append(expectedInnerClasses); message.append("\n\tActual : "); message.append(actualInnerClasses); message.append("\n"); assertEquals(message.toString() + "Number of inner classes should be equal", expectedInnerClasses.size(), actualInnerClasses.size()); for (int i = 0; i < expectedInnerClasses.size(); i++) { assertClassesEqual((JavaClass) expectedInnerClasses.get(i), (JavaClass) actualInnerClasses.get(i)); } } /** * Compares implemented interfaces from an actual class to an expected one. *

*

The implemented interfaces are sorted by name before comparison to be sure * that even if the implemented interfaces are defined in a different order, the * comparison is still right.

*/ private static void assertInterfacesEqual(JavaClass expected, JavaClass actual) { List expectedImplements = Arrays.asList(expected.getImplements()); Collections.sort(expectedImplements); List actualImplements = Arrays.asList(actual.getImplements()); Collections.sort(actualImplements); StringBuffer message = new StringBuffer("-> assertInnerClassesEquals"); message.append("\n\tExcepted : "); message.append(expectedImplements); message.append("\n\tActual : "); message.append(actualImplements); message.append("\n"); assertEquals(message.toString() + "Number of implemented interface should be equal", expectedImplements.size(), actualImplements.size()); for (int i = 0; i < expectedImplements.size(); i++) { assertEquals("Implemented interface should be equal", expectedImplements.get(i), actualImplements.get(i)); } } /** * Compares constructors and methods from an actual class to an expected one. *

*

The constructors and the methods are sorted by name before comparison to be sure * that even if the constructors and methods are defined in a different order, the * comparison is still right.

*/ private static void assertMethodsEqual(JavaClass expected, JavaClass actual) { List expectedMethods = Arrays.asList(expected.getMethods()); Collections.sort(expectedMethods, ENTITY_COMPARATOR); List actualMethods = Arrays.asList(actual.getMethods()); Collections.sort(actualMethods, ENTITY_COMPARATOR); StringBuffer message = new StringBuffer("-> assertMethodsEqual"); message.append("\n\tExcepted : "); message.append(expectedMethods); message.append("\n\tActual : "); message.append(actualMethods); message.append("\n"); assertEquals(message.toString() + "Number of methods should be equal", expectedMethods.size(), actualMethods.size()); for (int i = 0; i < expectedMethods.size(); i++) { assertEquals("Method should be equal", expectedMethods.get(i), actualMethods.get(i)); } } /** * Compares modifiers an actual entity. *

*

The modifiers are sorted by name before comparison to be sure * that even if the modifiers are defined in a different order, the * comparison is still right.

*/ private static void assertModifiersEquals(String msg, AbstractJavaEntity expected, AbstractJavaEntity actual) { List expectedModifiers = Arrays.asList(expected.getModifiers()); Collections.sort(expectedModifiers); List actualModifiers = Arrays.asList(actual.getModifiers()); Collections.sort(actualModifiers); StringBuffer message = new StringBuffer("-> assertModifiersEquals"); message.append("\n\tExcepted : "); message.append(expectedModifiers); message.append("\n\tActual : "); message.append(actualModifiers); message.append("\n"); assertEquals(message.toString() + msg + "\nNumber of modifiers should be equal", expectedModifiers.size(), actualModifiers.size()); for (int i = 0; i < expectedModifiers.size(); i++) { assertEquals(msg + "\n" + message.toString() + "\nModifier should be equal", expectedModifiers.get(i), actualModifiers.get(i)); } } private static void assertNotDir(File expected, File actual) { if (expected.isDirectory()) fail(expected.getAbsolutePath() + " - should not have been a directory"); if (actual.isDirectory()) fail(actual.getAbsolutePath() + " - should not have been a directory"); } protected File getDir() { return ( new File(getClass() .getResource("/" + getClass().getName().replace('.', '/') + ".class") .getFile())) .getParentFile(); } protected File getRootDir() { File dir = getDir(); StringTokenizer st = new StringTokenizer(getClass().getName(), "."); for (int i = 0; i < st.countTokens() - 1; i++) { dir = dir.getParentFile(); } return dir; } } qdox-qdox-1.12.1/src/java/com/thoughtworks/qdox/model/000077500000000000000000000000001204551233600226325ustar00rootroot00000000000000qdox-qdox-1.12.1/src/java/com/thoughtworks/qdox/model/AbstractBaseJavaEntity.java000066400000000000000000000024321204551233600300330ustar00rootroot00000000000000package com.thoughtworks.qdox.model; import java.io.Serializable; public class AbstractBaseJavaEntity implements Serializable { protected String name; private Annotation[] annotations = new Annotation[0]; private int lineNumber = -1; protected JavaClassParent parent; public AbstractBaseJavaEntity() { super(); } public int getLineNumber() { return lineNumber; } public String getName() { return name; } public Annotation[] getAnnotations() { return annotations; } public void setName(String name) { this.name = name; } public void setAnnotations(Annotation[] annotations) { this.annotations = annotations; } public void setLineNumber(int lineNumber) { this.lineNumber = lineNumber; } /** * * @return * @deprecated */ public JavaClassParent getParent() { return parent; } /** * * @param parent * @deprecated */ public void setParent(JavaClassParent parent) { this.parent = parent; } /** * Not every entity has a parentClass, but AnnotationFieldRef requires access to it. * When used with JavaClass, don't confuse this with getSuperClass() * * @return the surrounding class */ public JavaClass getParentClass() { return null; } }qdox-qdox-1.12.1/src/java/com/thoughtworks/qdox/model/AbstractInheritableJavaEntity.java000066400000000000000000000007111204551233600314050ustar00rootroot00000000000000package com.thoughtworks.qdox.model; /** * @author Aslak Hellesøy * @version $Revision$ */ public abstract class AbstractInheritableJavaEntity extends AbstractJavaEntity { public DocletTag getTagByName(String name, boolean inherited) { DocletTag[] tags = getTagsByName(name, inherited); return tags.length > 0 ? tags[0] : null; } public abstract DocletTag[] getTagsByName(String name, boolean inherited); } qdox-qdox-1.12.1/src/java/com/thoughtworks/qdox/model/AbstractJavaEntity.java000066400000000000000000000140731204551233600272440ustar00rootroot00000000000000package com.thoughtworks.qdox.model; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; public abstract class AbstractJavaEntity extends AbstractBaseJavaEntity implements Comparable { protected List modifiers = new ArrayList(); private String comment; private DocletTag[] tags = new DocletTag[0]; private JavaClass parentClass; /** * Return list of modifiers as Strings. * (public, private, protected, final, abstract, static) */ public String[] getModifiers() { return (String[]) modifiers.toArray(new String[modifiers.size()]); } public String getComment() { return comment; } public DocletTag[] getTags() { return tags; } public DocletTag[] getTagsByName(String name) { List specifiedTags = new ArrayList(); for (int i = 0; i < tags.length; i++) { DocletTag docletTag = tags[i]; if (docletTag.getName().equals(name)) { specifiedTags.add(docletTag); } } return (DocletTag[]) specifiedTags.toArray(new DocletTag[specifiedTags.size()]); } public DocletTag getTagByName(String name) { for (int i = 0; i < tags.length; i++) { DocletTag docletTag = tags[i]; if (docletTag.getName().equals(name)) { return docletTag; } } return null; } /** * Convenience method for getTagByName(String).getNamedParameter(String) * that also checks for null tag. * @since 1.3 */ public String getNamedParameter(String tagName, String parameterName) { DocletTag tag = getTagByName(tagName); if(tag != null) { return tag.getNamedParameter(parameterName); } else { return null; } } void commentHeader(IndentBuffer buffer) { if (comment == null && (tags == null || tags.length == 0)) { return; } else { buffer.write("/**"); buffer.newline(); if (comment != null && comment.length() > 0) { buffer.write(" * "); buffer.write(comment.replaceAll("\n", "\n * ")); buffer.newline(); } if (tags != null && tags.length > 0) { if (comment != null && comment.length() > 0) { buffer.write(" *"); buffer.newline(); } for (int i = 0; i < tags.length; i++) { DocletTag docletTag = tags[i]; buffer.write(" * @"); buffer.write(docletTag.getName()); if (docletTag.getValue().length() > 0) { buffer.write(' '); buffer.write(docletTag.getValue()); } buffer.newline(); } } buffer.write(" */"); buffer.newline(); } } public String getCodeBlock() { IndentBuffer result = new IndentBuffer(); write(result); return result.toString(); } protected void write(IndentBuffer result) { commentHeader(result); writeBody(result); } protected abstract void writeBody(IndentBuffer result); public void setModifiers(String[] modifiers) { this.modifiers = Arrays.asList(modifiers); } public void setComment(String comment) { this.comment = comment; } public void setTags(List tagList) { this.tags = new DocletTag[tagList.size()]; tagList.toArray(this.tags); } //helper methods for querying the modifiers public boolean isAbstract() { return isModifierPresent("abstract"); } public boolean isPublic() { return isModifierPresent("public"); } public boolean isPrivate() { return isModifierPresent("private"); } public boolean isProtected() { return isModifierPresent("protected"); } public boolean isStatic() { return isModifierPresent("static"); } public boolean isFinal() { return isModifierPresent("final"); } public boolean isSynchronized() { return isModifierPresent("synchronized"); } public boolean isTransient() { return isModifierPresent("transient"); } /** * @since 1.4 */ public boolean isVolatile() { return isModifierPresent("volatile"); } /** * @since 1.4 */ public boolean isNative() { return isModifierPresent("native"); } /** * @since 1.4 */ public boolean isStrictfp() { return isModifierPresent("strictfp"); } private boolean isModifierPresent(String modifier) { return modifiers.contains(modifier); } protected void writeNonAccessibilityModifiers(IndentBuffer result) { // modifiers (anything else) for (Iterator iter = modifiers.iterator(); iter.hasNext();) { String modifier = (String) iter.next(); if (!modifier.startsWith("p")) { result.write(modifier); result.write(' '); } } } protected void writeAccessibilityModifier(IndentBuffer result) { for (Iterator iter = modifiers.iterator(); iter.hasNext();) { String modifier = (String) iter.next(); if (modifier.startsWith("p")) { result.write(modifier); result.write(' '); } } } protected void writeAllModifiers(IndentBuffer result) { for (Iterator iter = modifiers.iterator(); iter.hasNext();) { String modifier = (String) iter.next(); result.write(modifier); result.write(' '); } } public JavaSource getSource() { return parentClass.getParentSource(); } public void setParentClass( JavaClass parentClass ) { this.parentClass = parentClass; } public JavaClass getParentClass() { return parentClass; } } qdox-qdox-1.12.1/src/java/com/thoughtworks/qdox/model/Annotation.java000066400000000000000000000065431204551233600256170ustar00rootroot00000000000000package com.thoughtworks.qdox.model; import java.io.Serializable; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import java.util.Map.Entry; import com.thoughtworks.qdox.model.annotation.AnnotationValue; import com.thoughtworks.qdox.model.annotation.AnnotationVisitor; /** * * @author Eric Redmond */ public class Annotation implements AnnotationValue, Serializable { private final Type type; private final int lineNumber; /** * Annotation properties as AnnotationValues *

* This map contains the parsed AnnotationValue for each property and allows * access to the full parse tree, including typerefs and expressions. */ private final Map properties = new LinkedHashMap(); /** * Annotation properties as Parameters */ private final Map namedParameters = new LinkedHashMap(); private AbstractBaseJavaEntity context; public Annotation(Type type, AbstractBaseJavaEntity context, Map namedParameters, int lineNumber) { this.type = type; this.context = context; this.lineNumber = lineNumber; if(properties != null) { for(Iterator i = this.properties.entrySet().iterator(); i.hasNext(); ) { Entry entry = (Entry) i.next(); String name = (String) entry.getKey(); AnnotationValue value = (AnnotationValue) entry.getValue(); setProperty(name, value); } } } public Annotation( Type type, int line ) { this(type, null, null, line); } public void setProperty(String name, AnnotationValue value) { properties.put( name, value ); namedParameters.put( name, value.getParameterValue() ); } /** * @return the annotation type */ public Type getType() { return type; } /** * @param key name of a named-parameter * @return the corresponding value, * or null if no such named-parameter was present */ public Object getNamedParameter(String key) { return namedParameters.get( key ); } /** * @return a Map containing all the named-parameters */ public Map getNamedParameterMap() { return namedParameters; } public final AbstractBaseJavaEntity getContext() { return context; } public int getLineNumber() { return lineNumber; } public Object accept( AnnotationVisitor visitor ) { return visitor.visitAnnotation( this ); } public Object getParameterValue() { return this; } public Map getPropertyMap() { return properties; } public AnnotationValue getProperty(String name) { return (AnnotationValue) properties.get( name ); } public void setContext( AbstractBaseJavaEntity context ) { this.context = context; } public String toString() { StringBuffer result = new StringBuffer(); result.append('@'); result.append(type.getValue()); result.append('('); if( !namedParameters.isEmpty() ) { for(Iterator i = namedParameters.entrySet().iterator(); i.hasNext();) result.append( i.next() + ","); result.deleteCharAt( result.length()-1 ); } result.append(')'); return result.toString(); } } qdox-qdox-1.12.1/src/java/com/thoughtworks/qdox/model/BeanProperty.java000066400000000000000000000015011204551233600261040ustar00rootroot00000000000000package com.thoughtworks.qdox.model; /** * * @author Aslak Hellesøy * @version $Revision$ */ public class BeanProperty { private final String name; private JavaMethod accessor; private JavaMethod mutator; private Type type; public BeanProperty(String name) { this.name = name; } public String getName() { return name; } public void setType(Type type) { this.type = type; } public Type getType() { return type; } public JavaMethod getAccessor() { return accessor; } public void setAccessor(JavaMethod accessor) { this.accessor = accessor; } public JavaMethod getMutator() { return mutator; } public void setMutator(JavaMethod mutator) { this.mutator = mutator; } } qdox-qdox-1.12.1/src/java/com/thoughtworks/qdox/model/ClassLibrary.java000066400000000000000000000103461204551233600260730ustar00rootroot00000000000000package com.thoughtworks.qdox.model; import java.io.File; import java.io.IOException; import java.io.ObjectInputStream; import java.io.Serializable; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.TreeSet; import java.util.Map; import java.util.HashMap; /** * Important!! Be sure to add a classloader with the bootstrap classes. * *

* Normally you can generate your classLibrary like this:
* * ClassLibrary classLibrary = new ClassLibrary(); * classLibrary.addDefaultLoader(); * *

* *

* If you want full control over the classLoaders you might want to create your library like:
* * ClassLibrary classLibrary = new ClassLibrary( ClassLoader.getSystemClassLoader() ) * *

* * @author Joe Walnes * @author Aslak Hellesøy * @author Robert Scholte */ public class ClassLibrary implements Serializable { private final Set classNames = new TreeSet(); private final Map classNameToClassMap = new HashMap(); private boolean defaultClassLoadersAdded = false; private transient List classLoaders = new ArrayList(); private List sourceFolders = new ArrayList(); // /** * Remember to add bootstrap classes */ public ClassLibrary() {} /** * Remember to add bootstrap classes */ public ClassLibrary(ClassLoader loader) { classLoaders.add(loader); } public void add(String className) { classNames.add(className); } public boolean contains(String className) { if (classNames.contains(className)) { return true; } else if (getSourceFile(className) != null) { return true; } else { return getClass(className) != null; } } public File getSourceFile( String className ) { for(Iterator iterator = sourceFolders.iterator(); iterator.hasNext();) { File sourceFolder = (File) iterator.next(); String mainClassName = className.split( "\\$" )[0]; File classFile = new File(sourceFolder, mainClassName.replace( '.', File.separatorChar ) + ".java"); if ( classFile.exists() && classFile.isFile() ) { return classFile; } } return null; } public Class getClass(String className) { Class cachedClass = (Class) classNameToClassMap.get(className); if (cachedClass != null) { return cachedClass; } else { for (Iterator iterator = classLoaders.iterator(); iterator.hasNext();) { ClassLoader classLoader = (ClassLoader) iterator.next(); if (classLoader == null) { continue; } try { Class clazz = classLoader.loadClass(className); if (clazz != null) { classNameToClassMap.put(className, clazz); return clazz; } } catch (ClassNotFoundException e) { // continue } catch (NoClassDefFoundError e) { // continue } } } return null; } public Collection all() { return Collections.unmodifiableCollection(classNames); } public void addClassLoader(ClassLoader classLoader) { classLoaders.add(classLoader); } public void addDefaultLoader() { if (!defaultClassLoadersAdded) { classLoaders.add(getClass().getClassLoader()); classLoaders.add(Thread.currentThread().getContextClassLoader()); } defaultClassLoadersAdded = true; } public void addSourceFolder( File sourceFolder ) { sourceFolders.add( sourceFolder ); } private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); classLoaders = new ArrayList(); if (defaultClassLoadersAdded) { defaultClassLoadersAdded = false; addDefaultLoader(); } } } qdox-qdox-1.12.1/src/java/com/thoughtworks/qdox/model/DefaultDocletTag.java000066400000000000000000000030031204551233600266440ustar00rootroot00000000000000package com.thoughtworks.qdox.model; import com.thoughtworks.qdox.model.util.TagParser; import java.util.Map; public class DefaultDocletTag implements DocletTag { private final String name; private final String value; private final int lineNumber; private String[] parameters; private Map namedParameters; private AbstractBaseJavaEntity context; public DefaultDocletTag(String name, String value, AbstractBaseJavaEntity context, int lineNumber) { this.name = name; this.value = value; this.context = context; this.lineNumber = lineNumber; } public DefaultDocletTag(String name, String value) { this(name, value, null, 0); } public String getName() { return name; } public String getValue() { return value; } public String[] getParameters() { if (parameters == null) { parameters = TagParser.parseParameters(value); } return parameters; } public Map getNamedParameterMap() { if (namedParameters == null) { namedParameters = TagParser.parseNamedParameters(value); } return namedParameters; } public String getNamedParameter(String key) { return (String) getNamedParameterMap().get(key); } public final AbstractBaseJavaEntity getContext() { return context; } public int getLineNumber() { return lineNumber; } } qdox-qdox-1.12.1/src/java/com/thoughtworks/qdox/model/DefaultDocletTagFactory.java000066400000000000000000000007761204551233600302120ustar00rootroot00000000000000package com.thoughtworks.qdox.model; /** * @author Aslak Hellesøy * @version $Revision$ */ public class DefaultDocletTagFactory implements DocletTagFactory { public DocletTag createDocletTag( String tag, String text, AbstractBaseJavaEntity context, int lineNumber ) { return new DefaultDocletTag(tag, text, context, lineNumber); } public DocletTag createDocletTag(String tag, String text) { return createDocletTag(tag, text, null, 0); } } qdox-qdox-1.12.1/src/java/com/thoughtworks/qdox/model/DocletTag.java000066400000000000000000000020001204551233600253330ustar00rootroot00000000000000package com.thoughtworks.qdox.model; import java.io.Serializable; import java.util.Map; /** * @author Joe Walnes * @author Aslak Hellesøy * @version $Revision$ */ public interface DocletTag extends Serializable { /** * @return the tag name */ String getName(); /** * @return the full tag-value */ String getValue(); /** * @return an array of whitespace-separatedtag parameters */ String[] getParameters(); /** * @param key name of a named-parameter * @return the corresponding value, * or null if no such named-parameter was present */ String getNamedParameter(String key); /** * @return a Map containing all the named-parameters */ Map getNamedParameterMap(); /** * @return the line-number where the tag occurred */ int getLineNumber(); /** * @return the language element to which this tag applies * @since 1.4 */ AbstractBaseJavaEntity getContext(); } qdox-qdox-1.12.1/src/java/com/thoughtworks/qdox/model/DocletTagFactory.java000066400000000000000000000006341204551233600266760ustar00rootroot00000000000000package com.thoughtworks.qdox.model; import java.io.Serializable; /** * @author Aslak Hellesøy * @version $Revision$ */ public interface DocletTagFactory extends Serializable { /** * @since 1.5 */ DocletTag createDocletTag( String tag, String text, AbstractBaseJavaEntity context, int lineNumber ); DocletTag createDocletTag(String tag, String text); } qdox-qdox-1.12.1/src/java/com/thoughtworks/qdox/model/IndentBuffer.java000066400000000000000000000014301204551233600260460ustar00rootroot00000000000000package com.thoughtworks.qdox.model; public class IndentBuffer { private StringBuffer buffer = new StringBuffer(); private int depth = 0; private boolean newLine; public void write(String s) { checkNewLine(); buffer.append(s); } public void write(char s) { checkNewLine(); buffer.append(s); } public void newline() { buffer.append('\n'); newLine = true; } public void indent() { depth++; } public void deindent() { depth--; } public String toString() { return buffer.toString(); } private void checkNewLine() { if (newLine) { for (int i = 0; i < depth; i++) buffer.append('\t'); newLine = false; } } } qdox-qdox-1.12.1/src/java/com/thoughtworks/qdox/model/JavaClass.java000066400000000000000000000517521204551233600253560ustar00rootroot00000000000000package com.thoughtworks.qdox.model; import com.thoughtworks.qdox.JavaClassContext; import com.thoughtworks.qdox.model.util.OrderedMap; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; /** * @author Joe Walnes * @author Aslak Hellesøy */ public class JavaClass extends AbstractInheritableJavaEntity implements JavaClassParent { private static Type OBJECT = new Type("java.lang.Object"); private static Type ENUM = new Type("java.lang.Enum"); private static Type ANNOTATION = new Type("java.lang.annotation.Annotation"); private List methods = new LinkedList(); private JavaMethod[] methodsArray; private List fields = new LinkedList(); private JavaField[] fieldsArray; private List classes = new LinkedList(); private JavaClass[] classesArray; private boolean interfce; private boolean isEnum; private boolean isAnnotation; // Don't access this directly. Use asType() to get my Type private Type type; private Type superClass; private Type[] implementz = new Type[0]; private TypeVariable[] typeParameters = TypeVariable.EMPTY_ARRAY; private JavaClassContext context; //sourceless class can use this property private JavaPackage javaPackage; private JavaSource source; public JavaClass() { } public JavaClass(String name) { setName(name); } public void setJavaClassContext(JavaClassContext context) { this.context = context; // reassign OBJECT. This will make it have a "source" too, // causing Type.getJavaClass() to return a JavaClass, instead // of null. OBJECT = context.getClassByName("java.lang.Object").asType(); } /** * is interface? (otherwise enum or class) */ public boolean isInterface() { return interfce; } /** * is enum? (otherwise class or interface) */ public boolean isEnum() { return isEnum; } public Type getSuperClass() { boolean iAmJavaLangObject = OBJECT.equals(asType()); if (isEnum) { return ENUM; } else if (!interfce && !isAnnotation && (superClass == null) && !iAmJavaLangObject) { return OBJECT; } return superClass; } /** * Shorthand for getSuperClass().getJavaClass() with null checking. */ public JavaClass getSuperJavaClass() { if (getSuperClass() != null) { return getSuperClass().getJavaClass(); } else { return null; } } public Type[] getImplements() { return implementz; } /** * @since 1.3 */ public JavaClass[] getImplementedInterfaces() { Type[] type = getImplements(); JavaClass[] result = new JavaClass[type.length]; for (int i = 0; i < result.length; i++) { result[i] = type[i].getJavaClass(); } return result; } protected void writeBody(IndentBuffer result) { writeAccessibilityModifier(result); writeNonAccessibilityModifiers(result); result.write(isEnum ? "enum " : interfce ? "interface " : isAnnotation ? "@interface " : "class "); result.write(name); // subclass if (superClass != null) { result.write(" extends "); result.write(superClass.getValue()); } // implements if (implementz.length > 0) { result.write(interfce ? " extends " : " implements "); for (int i = 0; i < implementz.length; i++) { if (i > 0) { result.write(", "); } result.write(implementz[i].getValue()); } } result.write(" {"); result.newline(); result.indent(); // fields for (Iterator iterator = fields.iterator(); iterator.hasNext();) { JavaField javaField = (JavaField) iterator.next(); result.newline(); javaField.write(result); } // methods for (Iterator iterator = methods.iterator(); iterator.hasNext();) { JavaMethod javaMethod = (JavaMethod) iterator.next(); result.newline(); javaMethod.write(result); } // inner-classes for (Iterator iterator = classes.iterator(); iterator.hasNext();) { JavaClass javaClass = (JavaClass) iterator.next(); result.newline(); javaClass.write(result); } result.deindent(); result.newline(); result.write('}'); result.newline(); } public void setInterface(boolean interfce) { this.interfce = interfce; } public void setEnum(boolean isEnum) { this.isEnum = isEnum; } public void setAnnotation(boolean isAnnotation) { this.isAnnotation = isAnnotation; } public void addMethod(JavaMethod meth) { meth.setParentClass( this ); methods.add(meth); methodsArray = null; } public void setSuperClass(Type type) { if (isEnum) throw new IllegalArgumentException("enums cannot extend other classes"); superClass = type; } public void setImplementz(Type[] implementz) { this.implementz = implementz; } public TypeVariable[] getTypeParameters() { return typeParameters; } public void setTypeParameters( TypeVariable[] typeParameters ) { this.typeParameters = typeParameters; } public void addField(JavaField javaField) { javaField.setParentClass( this ); fields.add(javaField); fieldsArray = null; } /** * Only used when constructing the model by hand / without source * * @param javaPackage */ public void setJavaPackage(JavaPackage javaPackage) { this.javaPackage = javaPackage; } public void setSource( JavaSource source ) { this.source = source; } public JavaSource getParentSource() { return (getParentClass() != null ? getParentClass().getParentSource() : source); } public JavaSource getSource() { return getParentSource(); } public JavaPackage getPackage() { return getParentSource() != null ? getParentSource().getPackage() : javaPackage; } public JavaClassParent getParent() { JavaClassParent result = getParentClass(); if (result == null) { result = getParentSource(); } return result; } /** * If this class has a package, the packagename will be returned. * Otherwise an empty String. * * @return */ public String getPackageName() { JavaPackage javaPackage = getPackage(); return (javaPackage != null && javaPackage.getName() != null) ? javaPackage.getName() : ""; } public String getFullyQualifiedName() { return (getParentClass() != null ? (getParentClass().getClassNamePrefix()) : getPackage() != null ? (getPackage().getName()+".") : "") + getName(); } /** * @since 1.3 */ public boolean isInner() { return getParentClass() != null; } public String resolveType(String typeName) { // Maybe it's an inner class? JavaClass[] innerClasses = getNestedClasses(); for (int i = 0; i < innerClasses.length; i++) { if (innerClasses[i].getName().equals(typeName)) { return innerClasses[i].getFullyQualifiedName(); } } return getParent().resolveType(typeName); } public JavaClassContext getJavaClassContext() { return getParent().getJavaClassContext(); } public String getClassNamePrefix() { return getFullyQualifiedName() + "$"; } public Type asType() { if (type == null) { type = new Type(getFullyQualifiedName(), 0, this); } return type; } public JavaMethod[] getMethods() { if (methodsArray == null) { methodsArray = new JavaMethod[methods.size()]; methods.toArray(methodsArray); } return methodsArray; } /** * @since 1.3 */ public JavaMethod[] getMethods(boolean superclasses) { if (superclasses) { Set signatures = new HashSet(); List methods = new ArrayList(); addMethodsFromSuperclassAndInterfaces(signatures, methods, this); return (JavaMethod[]) methods.toArray(new JavaMethod[methods.size()]); } else { return getMethods(); } } private void addMethodsFromSuperclassAndInterfaces(Set signatures, List methodList, JavaClass callingClazz) { JavaMethod[] methods = callingClazz.getMethods(); addNewMethods(signatures, methodList, methods); JavaClass superclass = callingClazz.getSuperJavaClass(); // TODO workaround for a bug in getSuperJavaClass if ((superclass != null) && (superclass != callingClazz)) { callingClazz.addMethodsFromSuperclassAndInterfaces(signatures, methodList, superclass); } JavaClass[] implementz = callingClazz.getImplementedInterfaces(); for (int i = 0; i < implementz.length; i++) { if (implementz[i] != null) { callingClazz.addMethodsFromSuperclassAndInterfaces(signatures, methodList, implementz[i]); } } } private void addNewMethods(Set signatures, List methodList, JavaMethod[] methods) { for (int i = 0; i < methods.length; i++) { JavaMethod method = methods[i]; if (!method.isPrivate()) { String signature = method.getDeclarationSignature(false); if (!signatures.contains(signature)) { methodList.add( new JavaMethodDelegate( this, method ) ); signatures.add(signature); } } } } /** * * @param name method name * @param parameterTypes parameter types or null if there are no parameters. * @return the matching method or null if no match is found. */ public JavaMethod getMethodBySignature(String name, Type[] parameterTypes) { return getMethod( name, parameterTypes, false ); } /** * This should be the signature for getMethodBySignature * * @param name * @param parameterTypes * @param varArgs * @return */ public JavaMethod getMethod(String name, Type[] parameterTypes, boolean varArgs) { JavaMethod[] methods = getMethods(); for (int i = 0; i < methods.length; i++) { if (methods[i].signatureMatches(name, parameterTypes, varArgs)) { return methods[i]; } } return null; } /** * * @param name * @param parameterTypes * @param superclasses * @return */ public JavaMethod getMethodBySignature(String name, Type[] parameterTypes, boolean superclasses) { return getMethodBySignature( name, parameterTypes, superclasses, false ); } /** * * @param name * @param parameterTypes * @param superclasses * @param varArg * @return */ public JavaMethod getMethodBySignature(String name, Type[] parameterTypes, boolean superclasses, boolean varArg) { JavaMethod[] result = getMethodsBySignature(name, parameterTypes, superclasses, varArg); return (result.length > 0) ? result[0] : null; } /** * * @param name * @param parameterTypes * @param superclasses * @return */ public JavaMethod[] getMethodsBySignature(String name, Type[] parameterTypes, boolean superclasses) { return getMethodsBySignature( name, parameterTypes, superclasses, false ); } /** * * @param name * @param parameterTypes * @param superclasses * @param varArg * @return */ public JavaMethod[] getMethodsBySignature(String name, Type[] parameterTypes, boolean superclasses, boolean varArg) { List result = new ArrayList(); JavaMethod methodInThisClass = getMethod(name, parameterTypes, varArg); if (methodInThisClass != null) { result.add(methodInThisClass); } if (superclasses) { JavaClass superclass = getSuperJavaClass(); if (superclass != null) { JavaMethod method = superclass.getMethodBySignature(name, parameterTypes, true, varArg ); // todo: ideally we should check on package privacy too. oh well. if ((method != null) && !method.isPrivate()) { result.add( new JavaMethodDelegate( this, method ) ); } } JavaClass[] implementz = getImplementedInterfaces(); for (int i = 0; i < implementz.length; i++) { JavaMethod method = implementz[i].getMethodBySignature(name, parameterTypes, true, varArg ); if (method != null) { result.add( new JavaMethodDelegate( this, method ) ); } } } return (JavaMethod[]) result.toArray(new JavaMethod[result.size()]); } public JavaField[] getFields() { if (fieldsArray == null) { fieldsArray = new JavaField[fields.size()]; fields.toArray(fieldsArray); } return fieldsArray; } public JavaField getFieldByName(String name) { JavaField[] fields = getFields(); for (int i = 0; i < fields.length; i++) { if (fields[i].getName().equals(name)) { return fields[i]; } } return null; } public void addClass(JavaClass cls) { cls.setParentClass( this ); classes.add(cls); classesArray = null; } /** * @deprecated Use {@link #getNestedClasses()} instead. */ public JavaClass[] getClasses() { return getNestedClasses(); } /** * @since 1.3 */ public JavaClass[] getNestedClasses() { if (classesArray == null) { classesArray = new JavaClass[classes.size()]; classes.toArray(classesArray); } return classesArray; } public JavaClass getNestedClassByName(String name) { JavaClass[] classes = getNestedClasses(); int separatorIndex = name.indexOf('.'); String directInnerClassName = (separatorIndex > 0 ? name.substring(0, separatorIndex) : name); for (int i = 0; i < classes.length; i++) { JavaClass jClass = classes[i]; if (jClass.getName().equals(directInnerClassName)) { if(separatorIndex > 0) { return jClass.getNestedClassByName(name.substring(separatorIndex+1)); } else { return jClass; } } } return null; } /** * @deprecated old name for {@link #getNestedClasses()} */ public JavaClass[] getInnerClasses() { return getNestedClasses(); } /** * @deprecated old name for {@link #getNestedClassByName(String)} */ public JavaClass getInnerClassByName(String name) { return getNestedClassByName(name); } /** * @since 1.3 */ public boolean isA(String fullClassName) { Type type = new Type(fullClassName, 0, this); return asType().isA(type); } /** * @since 1.3 */ public boolean isA(JavaClass javaClass) { return asType().isA(javaClass.asType()); } /** * Gets bean properties without looking in superclasses or interfaces. * * @since 1.3 */ public BeanProperty[] getBeanProperties() { return getBeanProperties(false); } /** * @since 1.3 */ public BeanProperty[] getBeanProperties(boolean superclasses) { Map beanPropertyMap = getBeanPropertyMap(superclasses); Collection beanPropertyCollection = beanPropertyMap.values(); return (BeanProperty[]) beanPropertyCollection.toArray(new BeanProperty[beanPropertyCollection .size()]); } private Map getBeanPropertyMap(boolean superclasses) { JavaMethod[] methods = getMethods(superclasses); Map beanPropertyMap = new OrderedMap(); // loop over the methods. for (int i = 0; i < methods.length; i++) { JavaMethod method = methods[i]; if (method.isPropertyAccessor()) { String propertyName = method.getPropertyName(); BeanProperty beanProperty = getOrCreateProperty(beanPropertyMap, propertyName); beanProperty.setAccessor(method); beanProperty.setType(method.getPropertyType()); } else if (method.isPropertyMutator()) { String propertyName = method.getPropertyName(); BeanProperty beanProperty = getOrCreateProperty(beanPropertyMap, propertyName); beanProperty.setMutator(method); beanProperty.setType(method.getPropertyType()); } } return beanPropertyMap; } private BeanProperty getOrCreateProperty(Map beanPropertyMap, String propertyName) { BeanProperty result = (BeanProperty) beanPropertyMap.get(propertyName); if (result == null) { result = new BeanProperty(propertyName); beanPropertyMap.put(propertyName, result); } return result; } /** * Gets bean property without looking in superclasses or interfaces. * * @since 1.3 */ public BeanProperty getBeanProperty(String propertyName) { return getBeanProperty(propertyName, false); } /** * @since 1.3 */ public BeanProperty getBeanProperty(String propertyName, boolean superclasses) { return (BeanProperty) getBeanPropertyMap(superclasses).get(propertyName); } /** * Gets the known derived classes. That is, subclasses or implementing classes. */ public JavaClass[] getDerivedClasses() { List result = new ArrayList(); JavaClass[] classes = context.getClasses(); for (int i = 0; i < classes.length; i++) { JavaClass clazz = classes[i]; if (clazz.isA(this) && !(clazz == this)) { result.add(clazz); } } return (JavaClass[]) result.toArray(new JavaClass[result.size()]); } public DocletTag[] getTagsByName(String name, boolean superclasses) { List result = new ArrayList(); addTagsRecursive(result, this, name, superclasses); return (DocletTag[]) result.toArray(new DocletTag[result.size()]); } private void addTagsRecursive(List result, JavaClass javaClass, String name, boolean superclasses) { DocletTag[] tags = javaClass.getTagsByName(name); addNewTags(result, tags); if (superclasses) { JavaClass superclass = javaClass.getSuperJavaClass(); // THIS IS A HACK AROUND A BUG THAT MUST BE SOLVED!!! // SOMETIMES A CLASS RETURNS ITSELF AS SUPER ?!?!?!?!?! if ((superclass != null) && (superclass != javaClass)) { addTagsRecursive(result, superclass, name, superclasses); } JavaClass[] implementz = javaClass.getImplementedInterfaces(); for (int h = 0; h < implementz.length; h++) { if (implementz[h] != null) { addTagsRecursive(result, implementz[h], name, superclasses); } } } } private void addNewTags(List list, DocletTag[] tags) { for (int i = 0; i < tags.length; i++) { DocletTag superTag = tags[i]; if (!list.contains(superTag)) { list.add(superTag); } } } public int compareTo(Object o) { return getFullyQualifiedName().compareTo(((JavaClass) o).getFullyQualifiedName()); } /** * @see http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Class.html#toString() */ public String toString() { StringBuffer sb = new StringBuffer(); if(asType().isPrimitive() || (Type.VOID.equals(asType()))) { sb.append(asType().getValue()); } else { sb.append(isInterface() ? "interface" : "class"); sb.append(" "); sb.append(getFullyQualifiedName()); } return sb.toString(); } } qdox-qdox-1.12.1/src/java/com/thoughtworks/qdox/model/JavaClassCache.java000066400000000000000000000004261204551233600262720ustar00rootroot00000000000000package com.thoughtworks.qdox.model; import java.io.Serializable; public interface JavaClassCache extends Serializable { public JavaClass[] getClasses(); public JavaClass getClassByName(String name); public void putClassByName(String name, JavaClass javaClass); } qdox-qdox-1.12.1/src/java/com/thoughtworks/qdox/model/JavaClassParent.java000066400000000000000000000011711204551233600265160ustar00rootroot00000000000000package com.thoughtworks.qdox.model; import com.thoughtworks.qdox.JavaClassContext; public interface JavaClassParent { /** * Resolve a type-name within the context of this source or class. * @param typeName name of a type * @return the fully-qualified name of the type, or null if it cannot * be resolved */ public String resolveType(String typeName); public JavaClassContext getJavaClassContext(); public String getClassNamePrefix(); public JavaSource getParentSource(); public void addClass(JavaClass cls); public JavaClass getNestedClassByName(String name); } qdox-qdox-1.12.1/src/java/com/thoughtworks/qdox/model/JavaField.java000066400000000000000000000050621204551233600253250ustar00rootroot00000000000000package com.thoughtworks.qdox.model; public class JavaField extends AbstractJavaEntity implements Member { private Type type; private String initializationExpression; public JavaField() { } public JavaField(String name) { setName(name); } public JavaField(Type type, String name) { setType(type); setName(name); } public Type getType() { return type; } protected void writeBody(IndentBuffer result) { writeAllModifiers(result); result.write(type.toString()); result.write(' '); result.write(name); if(initializationExpression != null && initializationExpression.length() > 0){ result.write(" = "); result.write(initializationExpression); } result.write(';'); result.newline(); } public void setType(Type type) { this.type = type; } public int compareTo(Object o) { return getName().compareTo(((JavaField)o).getName()); } public String getDeclarationSignature(boolean withModifiers) { IndentBuffer result = new IndentBuffer(); if (withModifiers) { writeAllModifiers(result); } result.write(type.toString()); result.write(' '); result.write(name); return result.toString(); } public String getCallSignature() { return getName(); } /** * Get the original expression used to initialize the field. * * @return initialization as string. */ public String getInitializationExpression(){ return initializationExpression; } public void setInitializationExpression(String initializationExpression){ this.initializationExpression = initializationExpression; } /** * @see http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Field.html#toString() */ public String toString() { StringBuffer result = new StringBuffer(); if(isPrivate()) { result.append("private "); } else if(isProtected()) { result.append("protected "); } else if(isPublic()) { result.append("public "); } if(isStatic()) { result.append("static "); } if(isFinal()) { result.append("final "); } if(isTransient()) { result.append("transient "); } if(isVolatile()) { result.append("volatile "); } result.append(getType().getValue() + " "); result.append(getParentClass().getFullyQualifiedName() + "." +getName()); return result.toString(); } } qdox-qdox-1.12.1/src/java/com/thoughtworks/qdox/model/JavaMethod.java000066400000000000000000000362071204551233600255270ustar00rootroot00000000000000package com.thoughtworks.qdox.model; import java.beans.Introspector; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; public class JavaMethod extends AbstractInheritableJavaEntity implements Member { private TypeVariable[] typeParameters = TypeVariable.EMPTY_ARRAY; private Type returns = Type.VOID; private List parameters = new LinkedList(); private JavaParameter[] parametersArray = JavaParameter.EMPTY_ARRAY; private Type[] exceptions = Type.EMPTY_ARRAY; private boolean constructor; private String sourceCode; private boolean varArgs; /** * The default constructor */ public JavaMethod() { } /** * Create new method without parameters and return type * * @param name the name of the method */ public JavaMethod(String name) { setName(name); } /** * Create a new method without parameters * * @param returns the return type * @param name the name of this method */ public JavaMethod(Type returns, String name) { setReturns(returns); setName(name); } /** * * @return the return type * @deprecated it is recommended to use getReturnType() */ public Type getReturns() { return returns; } public JavaParameter[] getParameters() { if(parametersArray == null) { parametersArray = new JavaParameter[parameters.size()]; parameters.toArray( parametersArray ); } return parametersArray; } public JavaParameter getParameterByName(String name) { JavaParameter[] parameters = getParameters(); for (int i = 0; i < parameters.length; i++) { if (parameters[i].getName().equals(name)) { return parameters[i]; } } return null; } public Type[] getExceptions() { return exceptions; } /** * * @return true is this method is a constructor */ public boolean isConstructor() { return constructor; } /** * * @return true is this method conains varArgs */ public boolean isVarArgs() { return varArgs; } protected void writeBody(IndentBuffer result) { writeBody(result, true, true, true); } /** * @since 1.3 */ protected void writeBody(IndentBuffer result, boolean withModifiers, boolean isDeclaration, boolean isPrettyPrint) { if (withModifiers) { writeAccessibilityModifier(result); writeNonAccessibilityModifiers(result); } if (!constructor) { if(isDeclaration) { result.write(returns.toString()); result.write(' '); } } result.write(name); result.write('('); for (int i = 0; i < getParameters().length; i++) { JavaParameter parameter = parametersArray[i]; if (i > 0) result.write(", "); if (isDeclaration) { result.write(parameter.getType().toString()); if (parameter.isVarArgs()) { result.write("..."); } result.write(' '); } result.write(parameter.getName()); } result.write(')'); if (isDeclaration && exceptions.length > 0) { result.write(" throws "); for (int i = 0; i < exceptions.length; i++) { if (i > 0) result.write(", "); result.write(exceptions[i].getValue()); } } if (isPrettyPrint) { if (sourceCode != null && sourceCode.length() > 0) { result.write(" {"); result.newline(); result.write(sourceCode); result.write("}"); result.newline(); } else { result.write(';'); result.newline(); } } } /** * @since 1.3 */ private String getSignature(boolean withModifiers, boolean isDeclaration) { IndentBuffer result = new IndentBuffer(); writeBody(result, withModifiers, isDeclaration, false); return result.toString(); } /** * @since 1.3 */ public String getDeclarationSignature(boolean withModifiers) { return getSignature(withModifiers, true); } /** * @since 1.3 */ public String getCallSignature() { return getSignature(false, false); } /** * Define the return type of this method * * @param returns the return type */ public void setReturns(Type returns) { this.returns = returns; } public void addParameter(JavaParameter javaParameter) { javaParameter.setParentMethod( this ); parameters.add( javaParameter ); parametersArray = null; this.varArgs = javaParameter.isVarArgs(); } public void setExceptions(Type[] exceptions) { this.exceptions = exceptions; } public void setConstructor(boolean constructor) { this.constructor = constructor; } public boolean equals(Object obj) { if ( this == obj ) { return true; } if ( !( obj instanceof JavaMethod ) ) { return false; } JavaMethod m = (JavaMethod) obj; if (m.isConstructor() != isConstructor()) { return false; } if ( m.getName() != null && !m.getName().equals( this.getName() ) ) { return false; } if ( this.getName() != null && !this.getName().equals( m.getName() ) ) { return false; } if ( m.getReturns() != null && !m.getReturns().equals( this.getReturns() ) ) { return false; } if ( this.getReturns() != null && !this.getReturns().equals( m.getReturns() ) ) { return false; } JavaParameter[] myParams = getParameters(); JavaParameter[] otherParams = m.getParameters(); if (otherParams.length != myParams.length) return false; for (int i = 0; i < myParams.length; i++) { if (!otherParams[i].equals(myParams[i])) return false; } return this.varArgs == m.varArgs; } /** * This method is NOT varArg aware. The overloaded method is. * * @param name * @param parameterTypes * @return * @deprecated use overloaded method */ public boolean signatureMatches(String name, Type[] parameterTypes) { return signatureMatches( name, parameterTypes, false ); } /** * @param name method name * @param parameterTypes parameter types or null if there are no parameters. * @return true if the signature and parameters match. */ public boolean signatureMatches(String name, Type[] parameterTypes, boolean varArg) { if (!name.equals(this.name)) return false; parameterTypes = (parameterTypes == null ? new Type[0] : parameterTypes); if (parameterTypes.length != this.getParameters().length) return false; for (int i = 0; i < parametersArray.length; i++) { if (!parametersArray[i].getType().equals(parameterTypes[i])) { return false; } } return (this.varArgs == varArg); } public int hashCode() { int hashCode = name.hashCode(); if (returns != null) hashCode *= returns.hashCode(); hashCode *= getParameters().length; return hashCode; } public boolean isPublic() { return super.isPublic() || (getParentClass() != null ? getParentClass().isInterface() : false); } /** * @return true if this method is a Java Bean accessor * @since 1.3 */ public boolean isPropertyAccessor() { if (isStatic()) return false; if (getParameters().length != 0) return false; if (getName().startsWith("is")) { return (getName().length() > 2 && Character.isUpperCase(getName().charAt(2))); } if (getName().startsWith("get")) { return (getName().length() > 3 && Character.isUpperCase(getName().charAt(3))); } return false; } /** * @return true if this method is a Java Bean accessor * @since 1.3 */ public boolean isPropertyMutator() { if (isStatic()) return false; if (getParameters().length != 1) return false; if (getName().startsWith("set")) { return (getName().length() > 3 && Character.isUpperCase(getName().charAt(3))); } return false; } /** * @return the type of the property this method represents, or null if this method * is not a property mutator or property accessor. * @since 1.3 */ public Type getPropertyType() { if (isPropertyAccessor()) { return getReturns(); } if (isPropertyMutator()) { return getParameters()[0].getType(); } return null; } /** * @return the name of the property this method represents, or null if this method * is not a property mutator or property accessor. * @since 1.3 */ public String getPropertyName() { int start = -1; if (getName().startsWith("get") || getName().startsWith("set")) { start = 3; } else if (getName().startsWith("is")) { start = 2; } else { return null; } return Introspector.decapitalize(getName().substring(start)); } public DocletTag[] getTagsByName(String name, boolean inherited) { JavaClass clazz = getParentClass(); JavaParameter[] params = getParameters(); Type[] types = new Type[params.length]; for (int i = 0; i < types.length; i++) { types[i] = params[i].getType(); } JavaMethod[] methods = clazz.getMethodsBySignature(getName(), types, true); List result = new ArrayList(); for (int i = 0; i < methods.length; i++) { JavaMethod method = methods[i]; DocletTag[] tags = method.getTagsByName(name); for (int j = 0; j < tags.length; j++) { DocletTag tag = tags[j]; if(!result.contains(tag)) { result.add(tag); } } } return (DocletTag[]) result.toArray(new DocletTag[result.size()]); } public int compareTo(Object o) { return getDeclarationSignature(false).compareTo(((JavaMethod)o).getDeclarationSignature(false)); } /** * Get the original source code of the body of this method. * * @return Code as string. */ public String getSourceCode(){ return sourceCode; } public void setSourceCode(String sourceCode){ this.sourceCode = sourceCode; } public void setTypeParameters(TypeVariable[] typeParameters) { this.typeParameters = typeParameters; } public TypeVariable[] getTypeParameters() { return typeParameters; } public String toString() { StringBuffer result = new StringBuffer(); if(isPrivate()) { result.append("private "); } else if(isProtected()) { result.append("protected "); } else if(isPublic()) { result.append("public "); } if(isAbstract()) { result.append("abstract "); } if(isStatic()) { result.append("static "); } if(isFinal()) { result.append("final "); } if(isSynchronized()) { result.append("synchronized "); } if(isNative()) { result.append("native "); } if (!constructor) { result.append(getReturns().getValue() + " "); } if(getParentClass() != null) { result.append(getParentClass().getFullyQualifiedName()); if (!constructor) { result.append("."); } } if (!constructor) { result.append(getName()); } result.append("("); for(int paramIndex=0;paramIndex0) { result.append(","); } String typeValue = getParameters()[paramIndex].getType().getResolvedValue(getTypeParameters()); result.append(typeValue); } result.append(")"); for(int i = 0; i < exceptions.length; i++) { result.append(i==0 ? " throws " : ","); result.append(exceptions[i].getValue()); } return result.toString(); } /** * Equivalent of java.lang.reflect.Method.getGenericReturnType() * * @return the generic returntype * @since 1.12 */ public Type getGenericReturnType() { return returns; } /** * Equivalent of java.lang.reflect.Method.getReturnType() * * @return * @since 1.12 */ public Type getReturnType() { return getReturnType( false ); } /** * If a class inherits this method from a generic class or interface, you can use this method to get the resolved return type * * @param resolve * @return * @since 1.12 */ public Type getReturnType( boolean resolve ) { return getReturnType( resolve, getParentClass() ); } /** * * @param resolve * @param callingClass * @return * @since 1.12 */ protected Type getReturnType ( boolean resolve, JavaClass callingClass) { Type result = null; if (getReturns() != null) { result = getReturns().resolve( this.getParentClass(), callingClass ); //According to java-specs, if it could be resolved the upper boundary, so Object, should be returned if ( !resolve && !returns.getFullyQualifiedName().equals( result.getFullyQualifiedName() ) ) { result = new Type( "java.lang.Object" ); } } return result; } /** * * @return the parameter types as array * @since 1.12 */ public Type[] getParameterTypes() { return getParameterTypes( false ); } /** * If a class inherits this method from a generic class or interface, you can use this method to get the resolved parameter types * * @param resolve * @return the parameter types as array * @since 1.12 */ public Type[] getParameterTypes( boolean resolve ) { return getParameterTypes( resolve, getParentClass() ); } protected Type[] getParameterTypes ( boolean resolve, JavaClass callingClass) { Type[] result = new Type[getParameters().length]; for (int paramIndex = 0; paramIndex < getParameters().length; paramIndex++ ) { Type curType = getParameters()[paramIndex].getType().resolve( this.getParentClass(), callingClass ); //According to java-specs, if it could be resolved the upper boundary, so Object, should be returned if ( !resolve && returns != null && !returns.getFullyQualifiedName().equals( curType.getFullyQualifiedName() ) ) { result[paramIndex] = new Type( "java.lang.Object" ); } else { result[paramIndex] = curType; } } return result; } } qdox-qdox-1.12.1/src/java/com/thoughtworks/qdox/model/JavaMethodDelegate.java000066400000000000000000000202361204551233600271550ustar00rootroot00000000000000package com.thoughtworks.qdox.model; import java.util.List; /** * This class can be used to access overridden methods while keeping a reference to the original class. * This is especially useful when trying to resolve generics * * @author Robert Scholte * @since 1.12 */ public class JavaMethodDelegate extends JavaMethod { private JavaClass callingClass; private JavaMethod originalMethod; public JavaMethodDelegate( JavaClass callingClass, JavaMethod originalMethod ) { this.callingClass = callingClass; this.originalMethod = originalMethod; } public Type getReturnType( boolean resolve ) { Type returnType = originalMethod.getReturnType( resolve, callingClass ); return returnType.resolve( originalMethod.getParentClass(), callingClass ); } protected Type getReturnType( boolean resolve, JavaClass _callingClass ) { //watch it!! use callingclass of constructor return super.getReturnType( resolve, this.callingClass ); } public Type[] getParameterTypes( boolean resolve ) { Type[] parameterTypes = originalMethod.getParameterTypes( resolve, callingClass ); for ( int paramIndex = 0; paramIndex < parameterTypes.length; paramIndex++ ) { parameterTypes[paramIndex] = parameterTypes[paramIndex].resolve( originalMethod.getParentClass(), callingClass ); } return parameterTypes; } protected Type[] getParameterTypes( boolean resolve, JavaClass _callingClass ) { //watch it!! use callingclass of constructor return super.getParameterTypes( resolve, this.callingClass ); } //Delegating methods public void addParameter( JavaParameter javaParameter ) { originalMethod.addParameter( javaParameter ); } public int compareTo( Object o ) { return originalMethod.compareTo( o ); } public boolean equals( Object obj ) { return originalMethod.equals( obj ); } public Annotation[] getAnnotations() { return originalMethod.getAnnotations(); } public String getCallSignature() { return originalMethod.getCallSignature(); } public String getCodeBlock() { return originalMethod.getCodeBlock(); } public String getComment() { return originalMethod.getComment(); } public String getDeclarationSignature( boolean withModifiers ) { return originalMethod.getDeclarationSignature( withModifiers ); } public Type[] getExceptions() { return originalMethod.getExceptions(); } public Type getGenericReturnType() { return originalMethod.getGenericReturnType(); } public int getLineNumber() { return originalMethod.getLineNumber(); } public String[] getModifiers() { return originalMethod.getModifiers(); } public String getName() { return originalMethod.getName(); } public String getNamedParameter( String tagName, String parameterName ) { return originalMethod.getNamedParameter( tagName, parameterName ); } public JavaParameter getParameterByName( String name ) { return originalMethod.getParameterByName( name ); } public JavaParameter[] getParameters() { return originalMethod.getParameters(); } public Type[] getParameterTypes() { return originalMethod.getParameterTypes(); } public JavaClassParent getParent() { return originalMethod.getParent(); } public JavaClass getParentClass() { return originalMethod.getParentClass(); } public String getPropertyName() { return originalMethod.getPropertyName(); } public Type getPropertyType() { return originalMethod.getPropertyType(); } public Type getReturns() { return originalMethod.getReturns(); } public Type getReturnType() { return getReturnType( false ); } public JavaSource getSource() { return originalMethod.getSource(); } public String getSourceCode() { return originalMethod.getSourceCode(); } public DocletTag getTagByName( String name, boolean inherited ) { return originalMethod.getTagByName( name, inherited ); } public DocletTag getTagByName( String name ) { return originalMethod.getTagByName( name ); } public DocletTag[] getTags() { return originalMethod.getTags(); } public DocletTag[] getTagsByName( String name, boolean inherited ) { return originalMethod.getTagsByName( name, inherited ); } public DocletTag[] getTagsByName( String name ) { return originalMethod.getTagsByName( name ); } public TypeVariable[] getTypeParameters() { return originalMethod.getTypeParameters(); } public int hashCode() { return originalMethod.hashCode(); } public boolean isAbstract() { return originalMethod.isAbstract(); } public boolean isConstructor() { return originalMethod.isConstructor(); } public boolean isFinal() { return originalMethod.isFinal(); } public boolean isNative() { return originalMethod.isNative(); } public boolean isPrivate() { return originalMethod.isPrivate(); } public boolean isPropertyAccessor() { return originalMethod.isPropertyAccessor(); } public boolean isPropertyMutator() { return originalMethod.isPropertyMutator(); } public boolean isProtected() { return originalMethod.isProtected(); } public boolean isPublic() { return originalMethod.isPublic(); } public boolean isStatic() { return originalMethod.isStatic(); } public boolean isStrictfp() { return originalMethod.isStrictfp(); } public boolean isSynchronized() { return originalMethod.isSynchronized(); } public boolean isTransient() { return originalMethod.isTransient(); } public boolean isVarArgs() { return originalMethod.isVarArgs(); } public boolean isVolatile() { return originalMethod.isVolatile(); } public void setAnnotations( Annotation[] annotations ) { originalMethod.setAnnotations( annotations ); } public void setComment( String comment ) { originalMethod.setComment( comment ); } public void setConstructor( boolean constructor ) { originalMethod.setConstructor( constructor ); } public void setExceptions( Type[] exceptions ) { originalMethod.setExceptions( exceptions ); } public void setLineNumber( int lineNumber ) { originalMethod.setLineNumber( lineNumber ); } public void setModifiers( String[] modifiers ) { originalMethod.setModifiers( modifiers ); } public void setName( String name ) { originalMethod.setName( name ); } public void setParent( JavaClassParent parent ) { originalMethod.setParent( parent ); } public void setParentClass( JavaClass parentClass ) { originalMethod.setParentClass( parentClass ); } public void setReturns( Type returns ) { originalMethod.setReturns( returns ); } public void setSourceCode( String sourceCode ) { originalMethod.setSourceCode( sourceCode ); } public void setTags( List tagList ) { originalMethod.setTags( tagList ); } public void setTypeParameters( TypeVariable[] typeParameters ) { originalMethod.setTypeParameters( typeParameters ); } public boolean signatureMatches( String name, Type[] parameterTypes, boolean varArg ) { return originalMethod.signatureMatches( name, parameterTypes, varArg ); } public boolean signatureMatches( String name, Type[] parameterTypes ) { return originalMethod.signatureMatches( name, parameterTypes ); } public String toString() { return originalMethod.toString(); } } qdox-qdox-1.12.1/src/java/com/thoughtworks/qdox/model/JavaPackage.java000066400000000000000000000061741204551233600256420ustar00rootroot00000000000000package com.thoughtworks.qdox.model; import java.util.ArrayList; import java.util.List; import java.util.Map; import com.thoughtworks.qdox.JavaClassContext; /** * A representation of a package. * @since 1.9 */ public class JavaPackage extends AbstractBaseJavaEntity { private JavaClassContext context; private String name; private Annotation[] annotations = new Annotation[0]; private int lineNumber = -1; private List classes = new ArrayList(); public JavaPackage() { } public JavaPackage(String name) { this(name, null); } /** * * @param name * @param allPackages * @deprecated allPackages is solved with the context */ public JavaPackage(String name, Map allPackages) { this.name= name; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Annotation[] getAnnotations() { return annotations; } public void setAnnotations(Annotation[] annotations) { this.annotations = annotations; } public int getLineNumber() { return lineNumber; } public void setLineNumber(int lineNumber) { this.lineNumber = lineNumber; } public void setContext( JavaClassContext context ) { this.context = context; } public void addClass(JavaClass clazz) { clazz.setJavaPackage(this); classes.add(clazz); } /** * Returns all the classes found for the package. * * @return all the classes found for the package */ public JavaClass[] getClasses() { //avoid infinitive recursion if (this == context.getPackageByName( name )) { return (JavaClass[]) classes.toArray(new JavaClass[classes.size()]); } else { return context.getPackageByName( name ).getClasses(); } } public JavaPackage getParentPackage() { String parentName = name.substring(0,name.lastIndexOf(".")); return (JavaPackage) context.getPackageByName( parentName ); } public JavaPackage[] getSubPackages() { String expected = name + "."; JavaPackage[] jPackages = context.getPackages(); List retList = new ArrayList(); for (int index = 0; index < jPackages.length;index++) { String pName = jPackages[index].getName(); if (pName.startsWith(expected) && !(pName.substring(expected.length()).indexOf(".") > -1)) { retList.add(context.getPackageByName( pName )); } } return (JavaPackage[]) retList.toArray(new JavaPackage[retList.size()]); } public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; JavaPackage that = (JavaPackage) o; if (!name.equals(that.name)) return false; return true; } public int hashCode() { return name.hashCode(); } /** * @see http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Package.html#toString() */ public String toString() { return "package " + name; } } qdox-qdox-1.12.1/src/java/com/thoughtworks/qdox/model/JavaParameter.java000066400000000000000000000036301204551233600262210ustar00rootroot00000000000000package com.thoughtworks.qdox.model; import java.io.Serializable; public class JavaParameter extends AbstractBaseJavaEntity implements Serializable { public static final JavaParameter[] EMPTY_ARRAY = new JavaParameter[0]; private String name; private Type type; private JavaMethod parentMethod; private boolean varArgs; public JavaParameter(Type type, String name) { this(type, name, false); } public JavaParameter(Type type, String name, boolean varArgs) { this.name = name; this.type = type; this.varArgs = varArgs; } public String getName() { return name; } public Type getType() { return type; } public boolean equals(Object obj) { JavaParameter p = (JavaParameter) obj; // name isn't used in equality check. return getType().equals(p.getType()); } public int hashCode() { return getType().hashCode(); } public JavaMethod getParentMethod() { return parentMethod; } public void setParentMethod(JavaMethod parentMethod) { this.parentMethod = parentMethod; } public JavaClass getParentClass() { return getParentMethod().getParentClass(); } /** * Is this a Java 5 var args type specified using three dots. e.g. void doStuff(Object... thing) * @since 1.6 */ public boolean isVarArgs() { return varArgs; } public String toString() { return getResolvedValue() + " "+ name; } /** * * @return the resolved value if the method has typeParameters, otherwise type's value * @since 1.10 */ public String getResolvedValue() { return type.getResolvedValue(getParentMethod().getTypeParameters()); } public String getResolvedGenericValue() { return type.getResolvedGenericValue(getParentMethod().getTypeParameters()); } } qdox-qdox-1.12.1/src/java/com/thoughtworks/qdox/model/JavaSource.java000066400000000000000000000231171204551233600255430ustar00rootroot00000000000000package com.thoughtworks.qdox.model; import java.io.File; import java.io.Serializable; import java.net.MalformedURLException; import java.net.URL; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.ListIterator; import java.util.Map; import java.util.Set; import com.thoughtworks.qdox.JavaClassContext; public class JavaSource implements Serializable, JavaClassParent { private static final Set PRIMITIVE_TYPES = new HashSet(); static { PRIMITIVE_TYPES.add("boolean"); PRIMITIVE_TYPES.add("byte"); PRIMITIVE_TYPES.add("char"); PRIMITIVE_TYPES.add("double"); PRIMITIVE_TYPES.add("float"); PRIMITIVE_TYPES.add("int"); PRIMITIVE_TYPES.add("long"); PRIMITIVE_TYPES.add("short"); PRIMITIVE_TYPES.add("void"); } private JavaPackage packge; private List imports = new LinkedList(); private String[] importsArray; private List classes = new LinkedList(); private JavaClass[] classesArray; private JavaClassContext context; private Map resolvedTypeCache = new HashMap(); private URL url; public JavaSource() { this(new JavaClassContext((ClassLibrary) null)); } public JavaSource(JavaClassContext context) { this.context = context; } /** * @since 1.4 */ public void setURL(URL url) { this.url = url; } /** * @since 1.4 */ public URL getURL() { return url; } /** * @deprecated use setURL */ public void setFile(File file) { try { setURL(file.toURL()); } catch (MalformedURLException e) { throw new IllegalStateException(e.getMessage()); } } /** * @deprecated use getURL */ public File getFile() { return new File(url.getFile()); } public JavaPackage getPackage() { return packge; } public void setPackage(JavaPackage packge) { this.packge = packge; } public void addImport(String imp) { imports.add(imp); importsArray = null; } public String[] getImports() { if (importsArray == null) { importsArray = new String[imports.size()]; imports.toArray(importsArray); } return importsArray; } public void addClass(JavaClass cls) { cls.setSource( this ); classes.add(cls); classesArray = null; } public JavaClass[] getClasses() { if (classesArray == null) { classesArray = new JavaClass[classes.size()]; classes.toArray(classesArray); } return classesArray; } public JavaClassContext getJavaClassContext() { return this.context; } public void setClassLibrary(ClassLibrary classLibrary) { this.context.setClassLibrary(classLibrary); } public String getCodeBlock() { IndentBuffer result = new IndentBuffer(); // package statement if (packge != null) { result.write("package "); result.write(packge.getName()); result.write(';'); result.newline(); result.newline(); } // import statement String[] imports = getImports(); for (int i = 0; imports != null && i < imports.length; i++) { result.write("import "); result.write(imports[i]); result.write(';'); result.newline(); } if (imports != null && imports.length > 0) { result.newline(); } // classes JavaClass[] classes = getClasses(); for (int i = 0; i < classes.length; i++) { if (i > 0) result.newline(); classes[i].write(result); } return result.toString(); } public String toString() { return getCodeBlock(); } public String resolveType(String typeName) { if (resolvedTypeCache.containsKey(typeName)) { return (String) resolvedTypeCache.get(typeName); } String resolved = resolveTypeInternal(typeName); if (resolved != null) { resolvedTypeCache.put(typeName, resolved); } return resolved; } /** * Resolves a type name *

* Follows the * Java Language Specification, Version 3.0. *

* Current resolution order is: *

    *
  1. Single-Type-Import Declaration
  2. *
  3. Type-Import-on-Demand Declaration
  4. *
  5. Automatic Imports
  6. *
* @todo Static imports are not handled yet * * @param typeName * @return Resolved type name */ private String resolveTypeInternal(String typeName) { String resolvedName = null; lookup : { // primitive types if(PRIMITIVE_TYPES.contains( typeName )) { resolvedName = typeName; break lookup; } String outerName = typeName; String nestedName = typeName.replace('.', '$'); int dotpos = typeName.indexOf( '.' ); if(dotpos >= 0) { outerName = typeName.substring( 0, dotpos ); } // Check single-type-import with fully qualified name resolvedName = resolveImportedType( typeName, nestedName, true ); if(resolvedName != null) { break lookup; } // Check single-type-import with outer name resolvedName = resolveImportedType( outerName, nestedName, false ); if(resolvedName != null) { break lookup; } // check for a class globally resolvedName = resolveFullyQualifiedType( typeName ); if(resolvedName != null) { break lookup; } if(context.getClassLibrary() != null) { // check for a class in the same package resolvedName = resolveFromLibrary( getClassNamePrefix() + nestedName ); if(resolvedName != null) { break lookup; } // try java.lang.* resolvedName = resolveFromLibrary( "java.lang." + nestedName ); if(resolvedName != null) { break lookup; } } // Check type-import-on-demand resolvedName = resolveImportedType( "*", nestedName, false ); if(resolvedName != null) { break lookup; } } return resolvedName; } private String resolveImportedType( String importSpec, String typeName, boolean fullMatch ) { String[] imports = getImports(); String resolvedName = null; String dotSuffix = "." + importSpec; for (int i = 0; i < imports.length && resolvedName == null; i++) { String imprt = imports[i]; //static imports can refer to inner classes if(imprt.startsWith( "static " ) ) { imprt = imprt.substring( 7 ); } if (imprt.equals(importSpec) || (!fullMatch && imprt.endsWith(dotSuffix))) { String candidateName = imprt.substring( 0, imprt.length() - importSpec.length()) + typeName; resolvedName = resolveFullyQualifiedType( candidateName ); if(resolvedName == null && !"*".equals(importSpec)) { resolvedName = candidateName; } } } return resolvedName; } private String resolveFromLibrary(String typeName) { return context.getClassLibrary().contains( typeName ) ? typeName : null; } private String resolveFullyQualifiedType(String typeName) { if (context.getClassLibrary() != null) { int indexOfLastDot = typeName.lastIndexOf('.'); if (indexOfLastDot >= 0) { String root = typeName.substring(0,indexOfLastDot); String leaf = typeName.substring(indexOfLastDot+1); String resolvedTypeName = resolveFullyQualifiedType(root + "$" + leaf); if(resolvedTypeName != null) { return resolvedTypeName; } } // check for fully-qualified class if (context.getClassLibrary().contains(typeName)) { return typeName; } } return null; } public String getClassNamePrefix() { if (getPackage() == null) return ""; return getPackage().getName() + "."; } public JavaSource getParentSource() { return this; } public JavaClass getNestedClassByName(String name) { JavaClass result = null; for (ListIterator i = classes.listIterator(); i.hasNext(); ) { JavaClass candidateClass = (JavaClass) i.next(); if (candidateClass.getName().equals(name)) { result = candidateClass; break; } } return result; } /** * * @return * @deprecated, use getJavaClassContext().getClassLibrary() */ public ClassLibrary getClassLibrary() { return this.context.getClassLibrary(); } public String getPackageName() { return (packge == null ? "" : packge.getName()); } } qdox-qdox-1.12.1/src/java/com/thoughtworks/qdox/model/Member.java000066400000000000000000000003511204551233600247030ustar00rootroot00000000000000package com.thoughtworks.qdox.model; /** * @author Aslak Hellesøy * @version $Revision$ * @since 1.4 */ public interface Member { String getDeclarationSignature(boolean withModifiers); String getCallSignature(); }qdox-qdox-1.12.1/src/java/com/thoughtworks/qdox/model/ModelBuilder.java000066400000000000000000000260761204551233600260570ustar00rootroot00000000000000package com.thoughtworks.qdox.model; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.ListIterator; import java.util.Map; import java.util.Set; import com.thoughtworks.qdox.JavaClassContext; import com.thoughtworks.qdox.model.annotation.AnnotationFieldRef; import com.thoughtworks.qdox.model.annotation.AnnotationVisitor; import com.thoughtworks.qdox.model.annotation.RecursiveAnnotationVisitor; import com.thoughtworks.qdox.parser.Builder; import com.thoughtworks.qdox.parser.structs.ClassDef; import com.thoughtworks.qdox.parser.structs.FieldDef; import com.thoughtworks.qdox.parser.structs.MethodDef; import com.thoughtworks.qdox.parser.structs.PackageDef; import com.thoughtworks.qdox.parser.structs.TagDef; import com.thoughtworks.qdox.parser.structs.TypeDef; import com.thoughtworks.qdox.parser.structs.TypeVariableDef; /** * @author Joe Walnes * @author Robert Scholte */ public class ModelBuilder implements Builder { private final JavaClassContext context; private final JavaSource source; private JavaClassParent currentParent; private JavaClass currentClass; private JavaMethod currentMethod; private List currentAnnoDefs; private String lastComment; private List lastTagSet; private DocletTagFactory docletTagFactory; public ModelBuilder() { this(new JavaClassContext(new ClassLibrary()), new DefaultDocletTagFactory(), new HashMap()); } public ModelBuilder(JavaClassContext context, DocletTagFactory docletTagFactory, Map allPackages) { this.context = context; this.docletTagFactory = docletTagFactory; source = new JavaSource(context); currentParent = source; currentAnnoDefs = new ArrayList(); } public void addPackage(PackageDef packageDef) { JavaPackage jPackage = context.getPackageByName( packageDef.name );; if (jPackage == null) { jPackage = new JavaPackage(packageDef.name); context.add( jPackage ); } jPackage.setLineNumber(packageDef.lineNumber); setAnnotations(jPackage); source.setPackage(jPackage); } public void addImport(String importName) { source.addImport(importName); } public void addJavaDoc(String text) { lastComment = text; lastTagSet = new LinkedList(); } public void addJavaDocTag(TagDef tagDef) { lastTagSet.add(tagDef); } public void beginClass(ClassDef def) { currentClass = new JavaClass(); currentClass.setLineNumber(def.lineNumber); // basic details currentClass.setName(def.name); currentClass.setInterface(ClassDef.INTERFACE.equals(def.type)); currentClass.setEnum(ClassDef.ENUM.equals(def.type)); currentClass.setAnnotation(ClassDef.ANNOTATION_TYPE.equals(def.type)); // superclass if (currentClass.isInterface()) { currentClass.setSuperClass(null); } else if (!currentClass.isEnum()) { currentClass.setSuperClass(def.extendz.size() > 0 ? createType((TypeDef) def.extendz.toArray()[0], 0) : null); } // implements { Set implementSet = currentClass.isInterface() ? def.extendz : def.implementz; Iterator implementIt = implementSet.iterator(); Type[] implementz = new Type[implementSet.size()]; for (int i = 0; i < implementz.length && implementIt.hasNext(); i++) { implementz[i] = createType((TypeDef) implementIt.next(), 0); } currentClass.setImplementz(implementz); } // modifiers { String[] modifiers = new String[def.modifiers.size()]; def.modifiers.toArray(modifiers); currentClass.setModifiers(modifiers); } // typeParameters if (def.typeParams != null) { TypeVariable[] typeParams = new TypeVariable[def.typeParams.size()]; int index = 0; for(Iterator iterator = def.typeParams.iterator(); iterator.hasNext();) { TypeVariableDef typeVariableDef = (TypeVariableDef) iterator.next(); typeParams[index++] = createTypeVariable(typeVariableDef); } currentClass.setTypeParameters(typeParams); } // javadoc addJavaDoc(currentClass); // // ignore annotation types (for now) // if (ClassDef.ANNOTATION_TYPE.equals(def.type)) { // System.out.println( currentClass.getFullyQualifiedName() ); // return; // } // annotations setAnnotations( currentClass ); currentParent.addClass(currentClass); currentParent = currentClass; context.add(currentClass.getFullyQualifiedName()); } public void endClass() { currentParent = currentClass.getParent(); if (currentParent instanceof JavaClass) { currentClass = (JavaClass) currentParent; } else { currentClass = null; } } public Type createType( String typeName, int dimensions ) { if( typeName == null || typeName.equals( "" ) ) return null; return createType(new TypeDef(typeName), dimensions); } public Type createType(TypeDef typeDef) { return createType(typeDef, 0); } /** * this one is specific for those cases where dimensions can be part of both the type and identifier * i.e. private String[] matrix[]; //field * public abstract String[] getMatrix[](); //method * * @param typeDef * @param dimensions * @return the Type */ public Type createType(TypeDef typeDef, int dimensions) { if(typeDef == null) { return null; } return Type.createUnresolved(typeDef, dimensions, currentClass == null ? currentParent : currentClass); } private void addJavaDoc(AbstractJavaEntity entity) { if (lastComment == null) return; entity.setComment(lastComment); Iterator tagDefIterator = lastTagSet.iterator(); List tagList = new ArrayList(); while (tagDefIterator.hasNext()) { TagDef tagDef = (TagDef) tagDefIterator.next(); tagList.add( docletTagFactory.createDocletTag( tagDef.name, tagDef.text, entity, tagDef.lineNumber ) ); } entity.setTags(tagList); lastComment = null; } public void addMethod(MethodDef def) { beginMethod(); endMethod(def); } public void beginMethod() { currentMethod = new JavaMethod(); setAnnotations(currentMethod); } public void endMethod(MethodDef def) { currentMethod.setParentClass(currentClass); currentMethod.setLineNumber(def.lineNumber); // basic details currentMethod.setName(def.name); currentMethod.setReturns(createType(def.returnType, def.dimensions)); currentMethod.setConstructor(def.constructor); // typeParameters if (def.typeParams != null) { TypeVariable[] typeParams = new TypeVariable[def.typeParams.size()]; int index = 0; for(Iterator iterator = def.typeParams.iterator(); iterator.hasNext();) { TypeVariableDef typeVariableDef = (TypeVariableDef) iterator.next(); typeParams[index++] = createTypeVariable(typeVariableDef); } currentMethod.setTypeParameters(typeParams); } // exceptions { Type[] exceptions = new Type[def.exceptions.size()]; int index = 0; for (Iterator iter = def.exceptions.iterator(); iter.hasNext();) { exceptions[index++] = createType((String) iter.next(), 0); } currentMethod.setExceptions(exceptions); } // modifiers { String[] modifiers = new String[def.modifiers.size()]; def.modifiers.toArray(modifiers); currentMethod.setModifiers(modifiers); } currentMethod.setSourceCode(def.body); // javadoc addJavaDoc(currentMethod); currentClass.addMethod(currentMethod); } public TypeVariable createTypeVariable(TypeVariableDef typeVariableDef) { if(typeVariableDef == null) { return null; } return TypeVariable.createUnresolved(typeVariableDef, currentClass == null ? currentParent : currentClass); } public TypeVariable createTypeVariable(String name, List typeParams) { if( name == null || name.equals( "" ) ) return null; return createTypeVariable(new TypeVariableDef(name, typeParams)); } public void addField(FieldDef def) { JavaField currentField = new JavaField(); currentField.setParentClass(currentClass); currentField.setLineNumber(def.lineNumber); currentField.setName(def.name); currentField.setType(createType(def.type, def.dimensions)); // modifiers { String[] modifiers = new String[def.modifiers.size()]; def.modifiers.toArray(modifiers); currentField.setModifiers(modifiers); } // code body currentField.setInitializationExpression(def.body); // javadoc addJavaDoc(currentField); // annotations setAnnotations( currentField ); currentClass.addField(currentField); } public void addParameter(FieldDef fieldDef) { JavaParameter jParam = new JavaParameter(createType(fieldDef.type, fieldDef.dimensions), fieldDef.name, fieldDef.isVarArgs); setAnnotations( jParam ); currentMethod.addParameter( jParam ); } private void setAnnotations( final AbstractBaseJavaEntity entity ) { if( !currentAnnoDefs.isEmpty() ) { AnnotationVisitor visitor = new RecursiveAnnotationVisitor() { public Object visitAnnotation( Annotation annotation ) { annotation.setContext( entity ); return super.visitAnnotation( annotation ); } public Object visitAnnotationFieldRef( AnnotationFieldRef fieldRef ) { fieldRef.setContext( entity ); return super.visitAnnotationFieldRef( fieldRef ); } }; Annotation[] annotations = new Annotation[currentAnnoDefs.size()]; for( ListIterator iter = currentAnnoDefs.listIterator(); iter.hasNext(); ) { Annotation annotation = (Annotation) iter.next(); annotation.accept(visitor); annotations[iter.previousIndex()] = annotation; } entity.setAnnotations( annotations ); currentAnnoDefs.clear(); } } // Don't resolve until we need it... class hasn't been defined yet. public void addAnnotation( Annotation annotation ) { currentAnnoDefs.add( annotation ); } public JavaSource getSource() { return source; } } qdox-qdox-1.12.1/src/java/com/thoughtworks/qdox/model/Type.java000066400000000000000000000312441204551233600244220ustar00rootroot00000000000000package com.thoughtworks.qdox.model; import java.io.Serializable; import com.thoughtworks.qdox.JavaClassContext; import com.thoughtworks.qdox.parser.structs.TypeDef; import com.thoughtworks.qdox.parser.structs.WildcardTypeDef; public class Type implements Comparable, Serializable { public static final Type[] EMPTY_ARRAY = new Type[0]; public static final Type VOID = new Type("void"); private String name; private JavaClassParent context; private String fullName; private int dimensions; private Type[] actualArgumentTypes; public Type(String fullName, String name, int dimensions, JavaClassParent context) { this.fullName = fullName; this.name = name; this.dimensions = dimensions; this.context = context; } public Type(String fullName, TypeDef typeDef, int dimensions, JavaClassParent context) { this.fullName = fullName; this.name = typeDef.name; this.dimensions = typeDef.dimensions + dimensions; //in some cases dimensions can be spread. Collect them here if(typeDef.actualArgumentTypes != null && !typeDef.actualArgumentTypes.isEmpty()) { actualArgumentTypes = new Type[typeDef.actualArgumentTypes.size()]; for(int index = 0; index < typeDef.actualArgumentTypes.size(); index++) { actualArgumentTypes[index] = createUnresolved((TypeDef) typeDef.actualArgumentTypes.get(index), context); } } this.context = context; } public Type(String fullName, int dimensions, JavaClassParent context) { this(fullName, (String) null, dimensions, context); } public Type(String fullName, int dimensions) { this(fullName, dimensions, null); } public Type(String fullName) { this(fullName, 0); } public static Type createUnresolved(String name, int dimensions, JavaClassParent context) { return new Type(null, name, dimensions, context); } public static Type createUnresolved(TypeDef typeDef, int dimensions, JavaClassParent context) { return new Type(null, typeDef, dimensions, context); } public static Type createUnresolved(TypeDef typeDef, JavaClassParent context) { if(typeDef instanceof WildcardTypeDef) { return new WildcardType((WildcardTypeDef) typeDef, context); } return new Type(null, typeDef, 0, context); } public JavaClassParent getJavaClassParent() { return context; } /** * * @deprecated instead use getFullyQualifiedName() */ public String getFullQualifiedName() { return getFullyQualifiedName(); } /** * Returns the FQN of an Object or the handler of a Type * If the name of the can't be resolved based on the imports and the classes on the classpath the name will be returned * InnerClasses will use the $ sign * * Some examples how names will be translated *
     * Object > java.lang.Object
     * java.util.List > java.util.List
     * ?  > ?
     * T  > T
     * anypackage.Outer.Inner > anypackage.Outer$Inner
     * 
* * @return */ public String getFullyQualifiedName() { return isResolved() ? fullName : name; } /** * The FQN representation of an Object for code usage * This implementation ignores generics * * Some examples how Objects will be translated *
     * Object > java.lang.object
     * java.util.List > java.util.List
     * ? > ?
     * T > T
     * anypackage.Outer.Inner > anypackage.Outer.Inner
     * 
* * @return type representation for code usage */ public String getValue() { String fqn = getFullyQualifiedName(); return ( fqn == null ? "" : fqn.replaceAll( "\\$", "." ) ); } /** * The FQN representation of an Object for code usage * This implementation ignores generics * * Some examples how Objects will be translated *
     * Object > java.lang.object
     * java.util.List > java.util.List
     * ? > ?
     * T > T
     * anypackage.Outer.Inner > anypackage.Outer.Inner
     * 
* @since 1.8 * @return generic type representation for code usage */ public String getGenericValue() { StringBuffer result = new StringBuffer(getValue()); if(actualArgumentTypes != null && actualArgumentTypes.length > 0) { result.append("<"); for(int index = 0;index < actualArgumentTypes.length; index++) { result.append(actualArgumentTypes[index].getGenericValue()); if(index + 1 != actualArgumentTypes.length) { result.append(","); } } result.append(">"); } for (int i = 0; i < dimensions; i++) result.append("[]"); return result.toString(); } protected String getGenericValue(TypeVariable[] typeVariableList) { StringBuffer result = new StringBuffer(getResolvedValue(typeVariableList)); if(actualArgumentTypes != null && actualArgumentTypes.length > 0) { for(int index = 0;index < actualArgumentTypes.length; index++) { result.append(actualArgumentTypes[index].getResolvedGenericValue(typeVariableList)); if(index + 1 != actualArgumentTypes.length) { result.append(","); } } } return result.toString(); } protected String getResolvedValue(TypeVariable[] typeParameters) { String result = getValue(); for(int typeIndex=0;typeIndex 0; } /** * Returns the depth of this array, 0 if it's not an array * * @return The depth of this array */ public int getDimensions() { return dimensions; } /** * * @return the actualTypeArguments or null */ public Type[] getActualTypeArguments() { return actualArgumentTypes; } /** * Returns getValue() extended with the array information * * @return */ public String toString() { if (dimensions == 0) return getValue(); StringBuffer buff = new StringBuffer(getValue()); for (int i = 0; i < dimensions; i++) buff.append("[]"); String result = buff.toString(); return result; } /** * Returns getGenericValue() extended with the array information * *
     * Object > java.lang.Object
     * Object[] > java.lang.Object[]
     * List > java.lang.List
     * Outer.Inner > Outer.Inner 
     * Outer.Inner[][] > Outer.Inner[][] 
     * 
     * @return 
     */
    public String toGenericString() {
        if (dimensions == 0) return getGenericValue();
        StringBuffer buff = new StringBuffer(getGenericValue());
        for (int i = 0; i < dimensions; i++) buff.append("[]");
        String result = buff.toString();
        return result;
    }

    public boolean equals(Object obj) {
        if (obj == null) return false;
        Type t = (Type) obj;
        return getValue().equals(t.getValue()) && t.getDimensions() == getDimensions();
    }

    public int hashCode() {
        return getValue().hashCode();
    }

    public JavaClass getJavaClass() {
    	JavaClass result = null;
    	
        JavaClassParent javaClassParent = getJavaClassParent();
        if (javaClassParent != null) {
        	result = javaClassParent.getNestedClassByName(getFullyQualifiedName());
	        if(result == null) {
	            JavaClassContext context = javaClassParent.getJavaClassContext();
	            if (context.getClassLibrary() != null) {
	            	result = context.getClassByName(getFullyQualifiedName());
	            }
	        }
        }
        return result;
    }

    /**
     * @since 1.3
     */
    public boolean isA(Type type) {
        if (this.equals(type)) {
            return true;
        } else {
            JavaClass javaClass = getJavaClass();
            if (javaClass != null) {
                // ask our interfaces
                Type[] implementz = javaClass.getImplements();
                for (int i = 0; i < implementz.length; i++) {
                    if (implementz[i].isA(type)) {
                        return true;
                    }
                }

                // ask our superclass
                Type supertype = javaClass.getSuperClass();
                if (supertype != null) {
                    if (supertype.isA(type)) {
                        return true;
                    }
                }
            }
        }
        // We'we walked up the hierarchy and found nothing.
        return false;
    }

    /**
     * @since 1.6
     */
    public boolean isPrimitive() {
        String value = getValue();
        if (value == null || value.length() == 0 || value.indexOf('.') > -1) {
            return false;
        } else {
           return "void".equals(value)           
            || "boolean".equals(value)
            || "byte".equals(value)
            || "char".equals(value)
            || "short".equals(value)
            || "int".equals(value)
            || "long".equals(value)
            || "float".equals(value)
            || "double".equals(value);
        }
    }

    /**
     * @since 1.6
     */
    public boolean isVoid() {
        return "void".equals(getValue());
    }

    /**
     * 
     * @param superClass
     * @return
     * @since 1.12
     */
    protected int getTypeVariableIndex( JavaClass superClass ) {
        TypeVariable[] typeVariables = superClass.getTypeParameters();
        for(int typeIndex=0;typeIndex= 0 )
        {
            String fqn = parentClass.getFullyQualifiedName();
            if ( subclass.getSuperClass() != null && fqn.equals( subclass.getSuperClass().getFullyQualifiedName() ) ) {
                result = subclass.getSuperClass().getActualTypeArguments()[typeIndex];    
            }
            else if ( subclass.getImplementedInterfaces() != null )
            {
                for ( int i = 0; i < subclass.getImplementedInterfaces().length; i++ )
                {
                    if ( fqn.equals( subclass.getImplements()[i].getFullyQualifiedName() ) ) 
                    {
                        result = subclass.getImplements()[i].getActualTypeArguments()[typeIndex].resolve( subclass.getImplementedInterfaces()[i] );
                        break;
                    }
                }
                //no direct interface available, try indirect
            }
        }
        
        if ( this.actualArgumentTypes != null ) {
            result = new Type( this.fullName, this.name, this.dimensions, this.context );
            
            result.actualArgumentTypes = new Type[this.actualArgumentTypes.length];
            for (int i = 0; i < this.getActualTypeArguments().length; i++ )
            {
                result.actualArgumentTypes[i] = this.actualArgumentTypes[i].resolve( parentClass, subclass );
            }
        }
        return result;
    }

}
qdox-qdox-1.12.1/src/java/com/thoughtworks/qdox/model/TypeVariable.java000066400000000000000000000027771204551233600261010ustar00rootroot00000000000000package com.thoughtworks.qdox.model;

import com.thoughtworks.qdox.parser.structs.TypeDef;
import com.thoughtworks.qdox.parser.structs.TypeVariableDef;
/**
 * 
 * 
 * @author Robert Scholte
 * @since 1.10
 */
public class TypeVariable extends Type {

	public static final TypeVariable[] EMPTY_ARRAY = new TypeVariable[0];
	
	private Type[] bounds;

	public TypeVariable(String fullName, TypeVariableDef def, JavaClassParent context) {
		super(fullName, def.name, 0, context);
		if(def.bounds != null && !def.bounds.isEmpty()) {
			bounds = new Type[def.bounds.size()];
        	for(int index = 0; index < def.bounds.size(); index++) {
        		bounds[index] = createUnresolved((TypeDef) def.bounds.get(index), context);
        	}
        }
	}

	public static TypeVariable createUnresolved(TypeVariableDef def, JavaClassParent context) {
		return new TypeVariable(null, def, context);
	}
	
	
	public String getValue() {
		return (bounds == null || bounds.length == 0 ? ""  : bounds[0].getValue());
	}
	
	public String getGenericValue() {
		StringBuffer result = new StringBuffer("<");
		result.append(super.getValue());
		if(bounds != null && bounds.length > 0) {
			result.append(" extends ");
			for(int index = 0; index < bounds.length; index++) {
				if(index > 0) {
					result.append(",");
				}
				result.append(bounds[index].getGenericValue());
			}
		}
		result.append(">");
		return result.toString();
	}
	
	public String getName() {
		return super.getValue();
	}

}
qdox-qdox-1.12.1/src/java/com/thoughtworks/qdox/model/WildcardType.java000066400000000000000000000015721204551233600260750ustar00rootroot00000000000000package com.thoughtworks.qdox.model;

import com.thoughtworks.qdox.parser.structs.WildcardTypeDef;

/**
 * This class supports both the 'super' and 'extends' wildcards.
 * For <?> you must use the normal Type, because ? itself can't be generic 
 * 
 * @author Robert Scholte
 *
 */
public class WildcardType extends Type {

	private String wildcardExpressionType = null;
	
	public WildcardType() {
		super("?");
	}
	
	
	public WildcardType(WildcardTypeDef typeDef) {
		this(typeDef, null);
	}

	public WildcardType(WildcardTypeDef typeDef, JavaClassParent context) {
		super(null, typeDef, 0, context);
		this.wildcardExpressionType = typeDef.getWildcardExpressionType();
	}

	public String getGenericValue() {
		String result = "";
		if(wildcardExpressionType != null) {
			result += "? " + wildcardExpressionType+ " ";
		}
		result += super.getGenericValue();
		return result;
	}
}
qdox-qdox-1.12.1/src/java/com/thoughtworks/qdox/model/annotation/000077500000000000000000000000001204551233600250045ustar00rootroot00000000000000qdox-qdox-1.12.1/src/java/com/thoughtworks/qdox/model/annotation/AnnotationAdd.java000066400000000000000000000011041204551233600303660ustar00rootroot00000000000000package com.thoughtworks.qdox.model.annotation;

public class AnnotationAdd extends AnnotationBinaryOperator {

    public AnnotationAdd( AnnotationValue left, AnnotationValue right ) {
        super( left, right );
    }

    public String toString() {
        return getLeft().toString() + " + " + getRight().toString();
    }

    public Object accept( AnnotationVisitor visitor ) {
        return visitor.visitAnnotationAdd( this );
    }

    public Object getParameterValue() {
        return getLeft().getParameterValue() + " + " + getRight().getParameterValue();
    }

}
qdox-qdox-1.12.1/src/java/com/thoughtworks/qdox/model/annotation/AnnotationAnd.java000066400000000000000000000011041204551233600304000ustar00rootroot00000000000000package com.thoughtworks.qdox.model.annotation;

public class AnnotationAnd extends AnnotationBinaryOperator {

    public AnnotationAnd( AnnotationValue left, AnnotationValue right ) {
        super( left, right );
    }

    public String toString() {
        return getLeft().toString() + " & " + getRight().toString();
    }

    public Object accept( AnnotationVisitor visitor ) {
        return visitor.visitAnnotationAnd( this );
    }

    public Object getParameterValue() {
        return getLeft().getParameterValue() + " & " + getRight().getParameterValue();
    }

}
qdox-qdox-1.12.1/src/java/com/thoughtworks/qdox/model/annotation/AnnotationBinaryOperator.java000066400000000000000000000007411204551233600326440ustar00rootroot00000000000000package com.thoughtworks.qdox.model.annotation;

public abstract class AnnotationBinaryOperator implements AnnotationValue {

    private AnnotationValue left;

    private AnnotationValue right;

    public AnnotationBinaryOperator( AnnotationValue left, AnnotationValue right ) {
        this.left = left;
        this.right = right;
    }

    public AnnotationValue getLeft() {
        return left;
    }

    public AnnotationValue getRight() {
        return right;
    }

}
qdox-qdox-1.12.1/src/java/com/thoughtworks/qdox/model/annotation/AnnotationCast.java000066400000000000000000000014641204551233600306010ustar00rootroot00000000000000package com.thoughtworks.qdox.model.annotation;

import com.thoughtworks.qdox.model.Type;

public class AnnotationCast implements AnnotationValue {

    private final Type type;

    private final AnnotationValue value;

    public AnnotationCast( Type type, AnnotationValue value ) {
        this.type = type;
        this.value = value;
    }

    public Type getType() {
        return this.type;
    }

    public AnnotationValue getValue() {
        return this.value;
    }

    public Object accept( AnnotationVisitor visitor ) {
        return visitor.visitAnnotationCast( this );
    }

    public Object getParameterValue() {
        return "(" + type.getValue() + ") " + value.getParameterValue();
    }

    public String toString() {
        return "(" + type.getValue() + ") " + value.toString();
    }

}
qdox-qdox-1.12.1/src/java/com/thoughtworks/qdox/model/annotation/AnnotationConstant.java000066400000000000000000000013141204551233600314720ustar00rootroot00000000000000package com.thoughtworks.qdox.model.annotation;

import java.io.Serializable;

public class AnnotationConstant implements AnnotationValue, Serializable {

    private final Object value;

    private final String image;

    public AnnotationConstant( Object value, String image ) {
        this.value = value;
        this.image = image;
    }

    public Object getValue() {
        return value;
    }

    public String getImage() {
        return image;
    }

    public String toString() {
        return image;
    }

    public Object accept( AnnotationVisitor visitor ) {
        return visitor.visitAnnotationConstant( this );
    }

    public Object getParameterValue() {
        return image;
    }

}
qdox-qdox-1.12.1/src/java/com/thoughtworks/qdox/model/annotation/AnnotationDivide.java000066400000000000000000000011151204551233600311040ustar00rootroot00000000000000package com.thoughtworks.qdox.model.annotation;

public class AnnotationDivide extends AnnotationBinaryOperator {

    public AnnotationDivide( AnnotationValue left, AnnotationValue right ) {
        super( left, right );
    }

    public String toString() {
        return getLeft().toString() + " / " + getRight().toString();
    }

    public Object accept( AnnotationVisitor visitor ) {
        return visitor.visitAnnotationDivide( this );
    }

    public Object getParameterValue() {
        return getLeft().getParameterValue() + " / " + getRight().getParameterValue();
    }

}
qdox-qdox-1.12.1/src/java/com/thoughtworks/qdox/model/annotation/AnnotationEquals.java000066400000000000000000000011171204551233600311340ustar00rootroot00000000000000package com.thoughtworks.qdox.model.annotation;

public class AnnotationEquals extends AnnotationBinaryOperator {

    public AnnotationEquals( AnnotationValue left, AnnotationValue right ) {
        super( left, right );
    }

    public String toString() {
        return getLeft().toString() + " == " + getRight().toString();
    }

    public Object accept( AnnotationVisitor visitor ) {
        return visitor.visitAnnotationEquals( this );
    }

    public Object getParameterValue() {
        return getLeft().getParameterValue() + " == " + getRight().getParameterValue();
    }

}
qdox-qdox-1.12.1/src/java/com/thoughtworks/qdox/model/annotation/AnnotationExclusiveOr.java000066400000000000000000000011341204551233600321510ustar00rootroot00000000000000package com.thoughtworks.qdox.model.annotation;

public class AnnotationExclusiveOr extends AnnotationBinaryOperator {

    public AnnotationExclusiveOr( AnnotationValue left, AnnotationValue right ) {
        super( left, right );
    }

    public String toString() {
        return getLeft().toString() + " ^ " + getRight().toString();
    }

    public Object accept( AnnotationVisitor visitor ) {
        return visitor.visitAnnotationExclusiveOr( this );
    }

    public Object getParameterValue() {
        return getLeft().getParameterValue() + " ^ " + getRight().getParameterValue();
    }

}
qdox-qdox-1.12.1/src/java/com/thoughtworks/qdox/model/annotation/AnnotationFieldRef.java000066400000000000000000000100761204551233600313660ustar00rootroot00000000000000package com.thoughtworks.qdox.model.annotation;

import java.lang.annotation.Documented;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.StringTokenizer;

import com.thoughtworks.qdox.model.AbstractBaseJavaEntity;
import com.thoughtworks.qdox.model.AbstractJavaEntity;
import com.thoughtworks.qdox.model.JavaClass;
import com.thoughtworks.qdox.model.JavaClassParent;
import com.thoughtworks.qdox.model.JavaField;
import com.thoughtworks.qdox.model.Type;

public class AnnotationFieldRef implements AnnotationValue {

    String[] myArray = new String[]{"unchecked"};
    private final int[] parts;

    private final String name;

    private AbstractBaseJavaEntity context;

    private JavaField field;

    private int fieldIndex = -1;

    public AnnotationFieldRef( String name ) {
        this.name = name;

        int length = new StringTokenizer( name, "." ).countTokens();
        this.parts = new int[length + 1];
        this.parts[0] = -1;

        for( int i = 1; i < length; ++i ) {
            this.parts[i] = name.indexOf( '.', this.parts[i - 1] + 1 );
        }

        this.parts[length] = name.length();
    }

    public String getName() {
        return name;
    }

    public String getNamePrefix( int end ) {
        return name.substring( 0, parts[end + 1] );
    }

    public String getNamePart( int index ) {
        return name.substring( parts[index] + 1, parts[index + 1] );
    }

    public int getPartCount() {
        return parts.length - 1;
    }

    public Object accept( AnnotationVisitor visitor ) {
        return visitor.visitAnnotationFieldRef( this );
    }

    public Object getParameterValue() {
        return getName();
    }

    public String toString() {
        return getName();
    }

    public AbstractBaseJavaEntity getContext() {
        return this.context;
    }

    public void setContext( AbstractBaseJavaEntity context ) {
        this.context = context;
    }

    public String getClassPart() {
        String result = null;

        if( getField() != null ) {
            result = name.substring( 0, parts[fieldIndex] );
        }

        return result;
    }

    public String getFieldPart() {
        String result = null;

        if( getField() != null ) {
            result = name.substring( parts[fieldIndex] + 1 );
        }

        return result;
    }

    protected JavaField resolveField( JavaClass javaClass, int start, int end ) {
        JavaField field = null;

        for( int i = start; i < end; ++i ) {
            field = javaClass.getFieldByName( getNamePart( i ) );

            if( field == null ) {
                break;
            }

            javaClass = field.getType().getJavaClass();
        }

        return field;
    }

    public JavaField getField() {
        if( fieldIndex < 0 ) {
            if( context.getParentClass() != null ) {
                JavaClass javaClass = context.getParentClass();
                field = resolveField( javaClass, 0, parts.length -1 );
                fieldIndex = 0;
            }

            if( field == null ) {
                JavaClassParent classParent = context.getParentClass();

                //assume context is a JavaClass itself
                if(classParent == null) {
                    classParent = (JavaClass) context;
                }
                
                for( int i = 0; i < parts.length - 1; ++i ) {
                    String className = getNamePrefix( i );
                    String typeName = classParent.resolveType( className );

                    if( typeName != null ) {
                        Type type = Type.createUnresolved( typeName, 0, classParent );
                        JavaClass javaClass = type.getJavaClass();

                        if( javaClass != null ) {
                            fieldIndex = i + 1;
                            field = resolveField( javaClass, i + 1, parts.length - 1 );
                            break;
                        }
                    }
                }
            }
        }

        return field;
    }
}
qdox-qdox-1.12.1/src/java/com/thoughtworks/qdox/model/annotation/AnnotationGreaterEquals.java000066400000000000000000000011441204551233600324460ustar00rootroot00000000000000package com.thoughtworks.qdox.model.annotation;

public class AnnotationGreaterEquals extends AnnotationBinaryOperator {

    public AnnotationGreaterEquals( AnnotationValue left, AnnotationValue right ) {
        super( left, right );
    }

    public String toString() {
        return getLeft().toString() + " >= " + getRight().toString();
    }

    public Object accept( AnnotationVisitor visitor ) {
        return visitor.visitAnnotationGreaterEquals( this );
    }

    public Object getParameterValue() {
        return getLeft().getParameterValue() + " >= " + getRight().getParameterValue();
    }

}
qdox-qdox-1.12.1/src/java/com/thoughtworks/qdox/model/annotation/AnnotationGreaterThan.java000066400000000000000000000011341204551233600321050ustar00rootroot00000000000000package com.thoughtworks.qdox.model.annotation;

public class AnnotationGreaterThan extends AnnotationBinaryOperator {

    public AnnotationGreaterThan( AnnotationValue left, AnnotationValue right ) {
        super( left, right );
    }

    public String toString() {
        return getLeft().toString() + " > " + getRight().toString();
    }

    public Object accept( AnnotationVisitor visitor ) {
        return visitor.visitAnnotationGreaterThan( this );
    }

    public Object getParameterValue() {
        return getLeft().getParameterValue() + " > " + getRight().getParameterValue();
    }

}
qdox-qdox-1.12.1/src/java/com/thoughtworks/qdox/model/annotation/AnnotationLessEquals.java000066400000000000000000000011331204551233600317610ustar00rootroot00000000000000package com.thoughtworks.qdox.model.annotation;

public class AnnotationLessEquals extends AnnotationBinaryOperator {

    public AnnotationLessEquals( AnnotationValue left, AnnotationValue right ) {
        super( left, right );
    }

    public String toString() {
        return getLeft().toString() + " <= " + getRight().toString();
    }

    public Object accept( AnnotationVisitor visitor ) {
        return visitor.visitAnnotationLessEquals( this );
    }

    public Object getParameterValue() {
        return getLeft().getParameterValue() + " <= " + getRight().getParameterValue();
    }

}
qdox-qdox-1.12.1/src/java/com/thoughtworks/qdox/model/annotation/AnnotationLessThan.java000066400000000000000000000011231204551233600314200ustar00rootroot00000000000000package com.thoughtworks.qdox.model.annotation;

public class AnnotationLessThan extends AnnotationBinaryOperator {

    public AnnotationLessThan( AnnotationValue left, AnnotationValue right ) {
        super( left, right );
    }

    public String toString() {
        return getLeft().toString() + " < " + getRight().toString();
    }

    public Object accept( AnnotationVisitor visitor ) {
        return visitor.visitAnnotationLessThan( this );
    }

    public Object getParameterValue() {
        return getLeft().getParameterValue() + " < " + getRight().getParameterValue();
    }

}
qdox-qdox-1.12.1/src/java/com/thoughtworks/qdox/model/annotation/AnnotationLogicalAnd.java000066400000000000000000000011331204551233600316750ustar00rootroot00000000000000package com.thoughtworks.qdox.model.annotation;

public class AnnotationLogicalAnd extends AnnotationBinaryOperator {

    public AnnotationLogicalAnd( AnnotationValue left, AnnotationValue right ) {
        super( left, right );
    }

    public String toString() {
        return getLeft().toString() + " && " + getRight().toString();
    }

    public Object accept( AnnotationVisitor visitor ) {
        return visitor.visitAnnotationLogicalAnd( this );
    }

    public Object getParameterValue() {
        return getLeft().getParameterValue() + " && " + getRight().getParameterValue();
    }

}
qdox-qdox-1.12.1/src/java/com/thoughtworks/qdox/model/annotation/AnnotationLogicalNot.java000066400000000000000000000007671204551233600317470ustar00rootroot00000000000000package com.thoughtworks.qdox.model.annotation;

public class AnnotationLogicalNot extends AnnotationUnaryOperator {

    public AnnotationLogicalNot( AnnotationValue value ) {
        super( value );
    }

    public String toString() {
        return "!" + getValue().toString();
    }

    public Object accept( AnnotationVisitor visitor ) {
        return visitor.visitAnnotationLogicalNot( this );
    }

    public Object getParameterValue() {
        return "!" + getValue().toString();
    }
}
qdox-qdox-1.12.1/src/java/com/thoughtworks/qdox/model/annotation/AnnotationLogicalOr.java000066400000000000000000000011301204551233600315500ustar00rootroot00000000000000package com.thoughtworks.qdox.model.annotation;

public class AnnotationLogicalOr extends AnnotationBinaryOperator {

    public AnnotationLogicalOr( AnnotationValue left, AnnotationValue right ) {
        super( left, right );
    }

    public String toString() {
        return getLeft().toString() + " || " + getRight().toString();
    }

    public Object accept( AnnotationVisitor visitor ) {
        return visitor.visitAnnotationLogicalOr( this );
    }

    public Object getParameterValue() {
        return getLeft().getParameterValue() + " || " + getRight().getParameterValue();
    }

}
qdox-qdox-1.12.1/src/java/com/thoughtworks/qdox/model/annotation/AnnotationMinusSign.java000066400000000000000000000007641204551233600316250ustar00rootroot00000000000000package com.thoughtworks.qdox.model.annotation;

public class AnnotationMinusSign extends AnnotationUnaryOperator {

    public AnnotationMinusSign( AnnotationValue value ) {
        super( value );
    }

    public String toString() {
        return "-" + getValue().toString();
    }

    public Object accept( AnnotationVisitor visitor ) {
        return visitor.visitAnnotationMinusSign( this );
    }

    public Object getParameterValue() {
        return "-" + getValue().toString();
    }
}
qdox-qdox-1.12.1/src/java/com/thoughtworks/qdox/model/annotation/AnnotationMultiply.java000066400000000000000000000011231204551233600315160ustar00rootroot00000000000000package com.thoughtworks.qdox.model.annotation;

public class AnnotationMultiply extends AnnotationBinaryOperator {

    public AnnotationMultiply( AnnotationValue left, AnnotationValue right ) {
        super( left, right );
    }

    public String toString() {
        return getLeft().toString() + " * " + getRight().toString();
    }

    public Object accept( AnnotationVisitor visitor ) {
        return visitor.visitAnnotationMultiply( this );
    }

    public Object getParameterValue() {
        return getLeft().getParameterValue() + " * " + getRight().getParameterValue();
    }

}
qdox-qdox-1.12.1/src/java/com/thoughtworks/qdox/model/annotation/AnnotationNot.java000066400000000000000000000007421204551233600304450ustar00rootroot00000000000000package com.thoughtworks.qdox.model.annotation;

public class AnnotationNot extends AnnotationUnaryOperator {

    public AnnotationNot( AnnotationValue value ) {
        super( value );
    }

    public String toString() {
        return "~" + getValue().toString();
    }

    public Object accept( AnnotationVisitor visitor ) {
        return visitor.visitAnnotationNot( this );
    }

    public Object getParameterValue() {
        return "~" + getValue().toString();
    }
}
qdox-qdox-1.12.1/src/java/com/thoughtworks/qdox/model/annotation/AnnotationNotEquals.java000066400000000000000000000011301204551233600316100ustar00rootroot00000000000000package com.thoughtworks.qdox.model.annotation;

public class AnnotationNotEquals extends AnnotationBinaryOperator {

    public AnnotationNotEquals( AnnotationValue left, AnnotationValue right ) {
        super( left, right );
    }

    public String toString() {
        return getLeft().toString() + " != " + getRight().toString();
    }

    public Object accept( AnnotationVisitor visitor ) {
        return visitor.visitAnnotationNotEquals( this );
    }

    public Object getParameterValue() {
        return getLeft().getParameterValue() + " != " + getRight().getParameterValue();
    }

}
qdox-qdox-1.12.1/src/java/com/thoughtworks/qdox/model/annotation/AnnotationOr.java000066400000000000000000000011011204551233600302530ustar00rootroot00000000000000package com.thoughtworks.qdox.model.annotation;

public class AnnotationOr extends AnnotationBinaryOperator {

    public AnnotationOr( AnnotationValue left, AnnotationValue right ) {
        super( left, right );
    }

    public String toString() {
        return getLeft().toString() + " | " + getRight().toString();
    }

    public Object accept( AnnotationVisitor visitor ) {
        return visitor.visitAnnotationOr( this );
    }

    public Object getParameterValue() {
        return getLeft().getParameterValue() + " | " + getRight().getParameterValue();
    }

}
qdox-qdox-1.12.1/src/java/com/thoughtworks/qdox/model/annotation/AnnotationParenExpression.java000066400000000000000000000011721204551233600330300ustar00rootroot00000000000000package com.thoughtworks.qdox.model.annotation;

public class AnnotationParenExpression implements AnnotationValue {

    private AnnotationValue value;

    public AnnotationParenExpression( AnnotationValue value ) {
        this.value = value;
    }

    public AnnotationValue getValue() {
        return value;
    }

    public String toString() {
        return "(" + value.toString() + ")";
    }

    public Object accept( AnnotationVisitor visitor ) {
        return visitor.visitAnnotationParenExpression( this );
    }

    public Object getParameterValue() {
        return "(" + value.getParameterValue() + ")";
    }

}
qdox-qdox-1.12.1/src/java/com/thoughtworks/qdox/model/annotation/AnnotationPlusSign.java000066400000000000000000000007611204551233600314520ustar00rootroot00000000000000package com.thoughtworks.qdox.model.annotation;

public class AnnotationPlusSign extends AnnotationUnaryOperator {

    public AnnotationPlusSign( AnnotationValue value ) {
        super( value );
    }

    public String toString() {
        return "+" + getValue().toString();
    }

    public Object accept( AnnotationVisitor visitor ) {
        return visitor.visitAnnotationPlusSign( this );
    }

    public Object getParameterValue() {
        return "+" + getValue().toString();
    }
}
qdox-qdox-1.12.1/src/java/com/thoughtworks/qdox/model/annotation/AnnotationQuery.java000066400000000000000000000023511204551233600310100ustar00rootroot00000000000000package com.thoughtworks.qdox.model.annotation;

public class AnnotationQuery implements AnnotationValue {

    private final AnnotationValue condition;

    private final AnnotationValue trueExpression;

    private final AnnotationValue falseExpression;

    public AnnotationQuery( AnnotationValue condition, AnnotationValue trueExpression, AnnotationValue falseExpression ) {
        this.condition = condition;
        this.trueExpression = trueExpression;
        this.falseExpression = falseExpression;
    }

    public Object accept( AnnotationVisitor visitor ) {
        return visitor.visitAnnotationQuery( this );
    }

    public AnnotationValue getCondition() {
        return this.condition;
    }

    public AnnotationValue getTrueExpression() {
        return this.trueExpression;
    }

    public AnnotationValue getFalseExpression() {
        return this.falseExpression;
    }

    public Object getParameterValue() {
        return condition.getParameterValue().toString() + " ? " + trueExpression.getParameterValue() + " : "
            + falseExpression.getParameterValue();
    }

    public String toString() {
        return condition.toString() + " ? " + trueExpression.toString() + " : " + falseExpression.toString();
    }
}
qdox-qdox-1.12.1/src/java/com/thoughtworks/qdox/model/annotation/AnnotationRemainder.java000066400000000000000000000011261204551233600316100ustar00rootroot00000000000000package com.thoughtworks.qdox.model.annotation;

public class AnnotationRemainder extends AnnotationBinaryOperator {

    public AnnotationRemainder( AnnotationValue left, AnnotationValue right ) {
        super( left, right );
    }

    public String toString() {
        return getLeft().toString() + " * " + getRight().toString();
    }

    public Object accept( AnnotationVisitor visitor ) {
        return visitor.visitAnnotationRemainder( this );
    }

    public Object getParameterValue() {
        return getLeft().getParameterValue() + " * " + getRight().getParameterValue();
    }

}
qdox-qdox-1.12.1/src/java/com/thoughtworks/qdox/model/annotation/AnnotationShiftLeft.java000066400000000000000000000011301204551233600315650ustar00rootroot00000000000000package com.thoughtworks.qdox.model.annotation;

public class AnnotationShiftLeft extends AnnotationBinaryOperator {

    public AnnotationShiftLeft( AnnotationValue left, AnnotationValue right ) {
        super( left, right );
    }

    public String toString() {
        return getLeft().toString() + " << " + getRight().toString();
    }

    public Object accept( AnnotationVisitor visitor ) {
        return visitor.visitAnnotationShiftLeft( this );
    }

    public Object getParameterValue() {
        return getLeft().getParameterValue() + " << " + getRight().getParameterValue();
    }

}
qdox-qdox-1.12.1/src/java/com/thoughtworks/qdox/model/annotation/AnnotationShiftRight.java000066400000000000000000000011331204551233600317530ustar00rootroot00000000000000package com.thoughtworks.qdox.model.annotation;

public class AnnotationShiftRight extends AnnotationBinaryOperator {

    public AnnotationShiftRight( AnnotationValue left, AnnotationValue right ) {
        super( left, right );
    }

    public String toString() {
        return getLeft().toString() + " >> " + getRight().toString();
    }

    public Object accept( AnnotationVisitor visitor ) {
        return visitor.visitAnnotationShiftRight( this );
    }

    public Object getParameterValue() {
        return getLeft().getParameterValue() + " >> " + getRight().getParameterValue();
    }

}
qdox-qdox-1.12.1/src/java/com/thoughtworks/qdox/model/annotation/AnnotationSubtract.java000066400000000000000000000011231204551233600314660ustar00rootroot00000000000000package com.thoughtworks.qdox.model.annotation;

public class AnnotationSubtract extends AnnotationBinaryOperator {

    public AnnotationSubtract( AnnotationValue left, AnnotationValue right ) {
        super( left, right );
    }

    public String toString() {
        return getLeft().toString() + " - " + getRight().toString();
    }

    public Object accept( AnnotationVisitor visitor ) {
        return visitor.visitAnnotationSubtract( this );
    }

    public Object getParameterValue() {
        return getLeft().getParameterValue() + " - " + getRight().getParameterValue();
    }

}
qdox-qdox-1.12.1/src/java/com/thoughtworks/qdox/model/annotation/AnnotationTypeRef.java000066400000000000000000000011271204551233600312610ustar00rootroot00000000000000package com.thoughtworks.qdox.model.annotation;

import com.thoughtworks.qdox.model.Type;

public class AnnotationTypeRef implements AnnotationValue {

    private Type type;

    public AnnotationTypeRef( Type type ) {
        this.type = type;
    }

    public Type getType() {
        return type;
    }

    public String toString() {
        return type.getValue() + ".class";
    }

    public Object accept( AnnotationVisitor visitor ) {
        return visitor.visitAnnotationTypeRef( this );
    }

    public Object getParameterValue() {
        return type.getValue() + ".class";
    }
}
qdox-qdox-1.12.1/src/java/com/thoughtworks/qdox/model/annotation/AnnotationUnaryOperator.java000066400000000000000000000005111204551233600325110ustar00rootroot00000000000000package com.thoughtworks.qdox.model.annotation;

public abstract class AnnotationUnaryOperator implements AnnotationValue {

    private AnnotationValue value;

    public AnnotationUnaryOperator( AnnotationValue value ) {
        this.value = value;
    }

    public AnnotationValue getValue() {
        return value;
    }

}
qdox-qdox-1.12.1/src/java/com/thoughtworks/qdox/model/annotation/AnnotationUnsignedShiftRight.java000066400000000000000000000011651204551233600334550ustar00rootroot00000000000000package com.thoughtworks.qdox.model.annotation;

public class AnnotationUnsignedShiftRight extends AnnotationBinaryOperator {

    public AnnotationUnsignedShiftRight( AnnotationValue left, AnnotationValue right ) {
        super( left, right );
    }

    public String toString() {
        return getLeft().toString() + " >>> " + getRight().toString();
    }

    public Object accept( AnnotationVisitor visitor ) {
        return visitor.visitAnnotationUnsignedShiftRight( this );
    }

    public Object getParameterValue() {
        return getLeft().getParameterValue() + " >>> " + getRight().getParameterValue();
    }

}
qdox-qdox-1.12.1/src/java/com/thoughtworks/qdox/model/annotation/AnnotationValue.java000066400000000000000000000010751204551233600307610ustar00rootroot00000000000000package com.thoughtworks.qdox.model.annotation;

import com.thoughtworks.qdox.model.Annotation;

/**
 * Interface for all annotation model elements
 * 
 * @author Jochen Kuhnle
 */
public interface AnnotationValue {

    /**
     * Accept a visitor for this value.
     * 
     * @param visitor Visitor
     * @return Visitor result
     */
    public Object accept( AnnotationVisitor visitor );

    /**
     * Get a parameter value for {@link Annotation#getNamedParameter(String)}.
     * 
     * @return Parameter value
     */
    public Object getParameterValue();

}
qdox-qdox-1.12.1/src/java/com/thoughtworks/qdox/model/annotation/AnnotationValueList.java000066400000000000000000000023761204551233600316220ustar00rootroot00000000000000package com.thoughtworks.qdox.model.annotation;

import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;

public class AnnotationValueList implements AnnotationValue {

    private final List valueList;

    public AnnotationValueList( List valueList ) {
        this.valueList = valueList;
    }

    public List getValueList() {
        return valueList;
    }

    public String toString() {
        StringBuffer buf = new StringBuffer();

        buf.append( "{" );

        int pos = buf.length();

        for( ListIterator i = valueList.listIterator(); i.hasNext(); ) {
            buf.append( i.next().toString() );
            buf.append( ", " );
        }

        if( buf.length() > pos ) {
            buf.setLength( buf.length() - 2 );
        }

        buf.append( "}" );

        return buf.toString();
    }

    public Object accept( AnnotationVisitor visitor ) {
        return visitor.visitAnnotationValueList( this );
    }

    public Object getParameterValue() {
        List list = new ArrayList();

        for( ListIterator i = valueList.listIterator(); i.hasNext(); ) {
            AnnotationValue value = (AnnotationValue) i.next();
            list.add( value.getParameterValue() );
        }

        return list;
    }
}
qdox-qdox-1.12.1/src/java/com/thoughtworks/qdox/model/annotation/AnnotationVisitor.java000066400000000000000000000047731204551233600313540ustar00rootroot00000000000000package com.thoughtworks.qdox.model.annotation;

import com.thoughtworks.qdox.model.Annotation;

/**
 * Visitor class for the annotation model elements
 * 
 * @author Jochen Kuhnle
 */
public interface AnnotationVisitor {

    public Object visitAnnotationAdd( AnnotationAdd add );

    public Object visitAnnotationSubtract( AnnotationSubtract subtract );

    public Object visitAnnotationMultiply( AnnotationMultiply multiply );

    public Object visitAnnotationDivide( AnnotationDivide divide );

    public Object visitAnnotationGreaterThan( AnnotationGreaterThan greaterThan );

    public Object visitAnnotationLessThan( AnnotationLessThan lessThan );

    public Object visitAnnotation( Annotation annotation );

    public Object visitAnnotationConstant( AnnotationConstant constant );

    public Object visitAnnotationParenExpression( AnnotationParenExpression expression );

    public Object visitAnnotationValueList( AnnotationValueList valueList );

    public Object visitAnnotationTypeRef( AnnotationTypeRef typeRef );

    public Object visitAnnotationFieldRef( AnnotationFieldRef fieldRef );

    public Object visitAnnotationLessEquals( AnnotationLessEquals lessEquals );

    public Object visitAnnotationGreaterEquals( AnnotationGreaterEquals greaterEquals );

    public Object visitAnnotationRemainder( AnnotationRemainder remainder );

    public Object visitAnnotationOr( AnnotationOr or );

    public Object visitAnnotationAnd( AnnotationAnd and );

    public Object visitAnnotationShiftLeft( AnnotationShiftLeft left );

    public Object visitAnnotationShiftRight( AnnotationShiftRight right );

    public Object visitAnnotationNot( AnnotationNot not );

    public Object visitAnnotationLogicalOr( AnnotationLogicalOr or );

    public Object visitAnnotationLogicalAnd( AnnotationLogicalAnd and );

    public Object visitAnnotationLogicalNot( AnnotationLogicalNot not );

    public Object visitAnnotationMinusSign( AnnotationMinusSign sign );

    public Object visitAnnotationPlusSign( AnnotationPlusSign sign );

    public Object visitAnnotationUnsignedShiftRight( AnnotationUnsignedShiftRight right );

    public Object visitAnnotationEquals( AnnotationEquals annotationEquals );

    public Object visitAnnotationNotEquals( AnnotationNotEquals annotationNotEquals );

    public Object visitAnnotationExclusiveOr( AnnotationExclusiveOr annotationExclusiveOr );

    public Object visitAnnotationQuery( AnnotationQuery annotationQuery );

    public Object visitAnnotationCast( AnnotationCast annotationCast );

}
qdox-qdox-1.12.1/src/java/com/thoughtworks/qdox/model/annotation/EvaluatingVisitor.java000066400000000000000000000632671204551233600313440ustar00rootroot00000000000000package com.thoughtworks.qdox.model.annotation;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.ListIterator;

import com.thoughtworks.qdox.model.Annotation;
import com.thoughtworks.qdox.model.JavaClass;
import com.thoughtworks.qdox.model.JavaField;

/**
 * Visitor that evaluates annotation expressions.
 * 

* Users of this class must override * {@link EvaluatingVisitor#getFieldReferenceValue(JavaField)} to return values * for referenced fields. * * @author Jochen Kuhnle */ public abstract class EvaluatingVisitor implements AnnotationVisitor { public Object getValue( Annotation annotation, String property ) { Object result = null; AnnotationValue value = annotation.getProperty( property ); if( value != null ) { result = value.accept( this ); } return result; } public List getListValue( Annotation annotation, String property ) { Object value = getValue( annotation, property ); List list = null; if( value != null ) { if( value instanceof List ) { list = (List) value; } else { list = Collections.singletonList( value ); } } return list; } /** * Return the result type of a binary operator *

* Performs binary numeric promotion as specified in the Java Language * Specification, * @see section 5.6.1 */ protected static Class resultType( Object left, Object right ) { Class type = void.class; if( left instanceof String || right instanceof String ) { type = String.class; } else if( left instanceof Number && right instanceof Number ) { if( left instanceof Double || right instanceof Double ) { type = Double.class; } else if( left instanceof Float || right instanceof Float ) { type = Float.class; } else if( left instanceof Long || right instanceof Long ) { type = Long.class; } else { type = Integer.class; } } return type; } /** * Return the numeric result type of a binary operator *

* Performs binary numeric promotion as specified in the Java Language * Specification, * @see section 5.6.1 */ protected static Class numericResultType( Object left, Object right ) { Class type = void.class; if( left instanceof Number && right instanceof Number ) { if( left instanceof Long || right instanceof Long ) { type = Long.class; } else if( left instanceof Integer || right instanceof Integer ) { type = Integer.class; } } return type; } /** * Return the result type of an unary operator *

* Performs unary numeric promotion as specified in the Java Language * Specification, * @see section 5.6.2 */ protected static Class unaryNumericResultType( Object value ) { Class type = void.class; if( value instanceof Byte || value instanceof Short || value instanceof Character || value instanceof Integer ) { type = Integer.class; } else if( value instanceof Long ) { value = Long.class; } return type; } protected static Class unaryResultType( Object value ) { Class type = unaryNumericResultType( value ); if( type == void.class ) { if( value instanceof Float ) { value = Float.class; } else if( value instanceof Double ) { value = Double.class; } } return type; } public Object visitAnnotation( Annotation annotation ) { throw new UnsupportedOperationException( "Illegal annotation value '" + annotation + "'." ); } public Object visitAnnotationAdd( AnnotationAdd op ) { Object left = op.getLeft().accept( this ); Object right = op.getRight().accept( this ); Class type = resultType( left, right ); Object result; if( type == String.class ) { result = left.toString() + right.toString(); } else if( type == Double.class ) { result = new Double( ((Number) left).doubleValue() + ((Number) right).doubleValue() ); } else if( type == Float.class ) { result = new Float( ((Number) left).floatValue() + ((Number) right).floatValue() ); } else if( type == Long.class ) { result = new Long( ((Number) left).longValue() + ((Number) right).longValue() ); } else if( type == Integer.class ) { result = new Integer( ((Number) left).intValue() + ((Number) right).intValue() ); } else { throw new IllegalArgumentException( "Cannot evaluate '" + op + "'." ); } return result; } public Object visitAnnotationConstant( AnnotationConstant constant ) { return constant.getValue(); } public Object visitAnnotationDivide( AnnotationDivide op ) { Object left = op.getLeft().accept( this ); Object right = op.getRight().accept( this ); Class type = resultType( left, right ); Object result; if( type == Double.class ) { result = new Double( ((Number) left).doubleValue() / ((Number) right).doubleValue() ); } else if( type == Float.class ) { result = new Float( ((Number) left).floatValue() / ((Number) right).floatValue() ); } else if( type == Long.class ) { result = new Long( ((Number) left).longValue() / ((Number) right).longValue() ); } else if( type == Integer.class ) { result = new Integer( ((Number) left).intValue() / ((Number) right).intValue() ); } else { throw new IllegalArgumentException( "Cannot evaluate '" + op + "'." ); } return result; } public Object visitAnnotationFieldRef( AnnotationFieldRef fieldRef ) { JavaField javaField = fieldRef.getField(); if( javaField == null ) { throw new IllegalArgumentException( "Cannot resolve field reference '" + fieldRef + "'." ); } if( !javaField.isFinal() || !javaField.isStatic() ) { throw new IllegalArgumentException( "Field reference '" + fieldRef + "' must be static and final." ); } Object result = getFieldReferenceValue( javaField ); return result; } protected abstract Object getFieldReferenceValue( JavaField javaField ); public Object visitAnnotationGreaterThan( AnnotationGreaterThan op ) { Object left = op.getLeft().accept( this ); Object right = op.getRight().accept( this ); Class type = resultType( left, right ); boolean result; if( type == Double.class ) { result = ((Number) left).doubleValue() > ((Number) right).doubleValue(); } else if( type == Float.class ) { result = ((Number) left).floatValue() > ((Number) right).floatValue(); } else if( type == Long.class ) { result = ((Number) left).longValue() > ((Number) right).longValue(); } else if( type == Integer.class ) { result = ((Number) left).intValue() > ((Number) right).intValue(); } else { throw new IllegalArgumentException( "Cannot evaluate '" + op + "'." ); } return result ? Boolean.TRUE : Boolean.FALSE; } public Object visitAnnotationLessThan( AnnotationLessThan op ) { Object left = op.getLeft().accept( this ); Object right = op.getRight().accept( this ); Class type = resultType( left, right ); boolean result; if( type == Double.class ) { result = ((Number) left).doubleValue() < ((Number) right).doubleValue(); } else if( type == Float.class ) { result = ((Number) left).floatValue() < ((Number) right).floatValue(); } else if( type == Long.class ) { result = ((Number) left).longValue() < ((Number) right).longValue(); } else if( type == Integer.class ) { result = ((Number) left).intValue() < ((Number) right).intValue(); } else { throw new IllegalArgumentException( "Cannot evaluate '" + op + "'." ); } return result ? Boolean.TRUE : Boolean.FALSE; } public Object visitAnnotationMultiply( AnnotationMultiply op ) { Object left = op.getLeft().accept( this ); Object right = op.getRight().accept( this ); Class type = resultType( left, right ); Object result; if( type == Double.class ) { result = new Double( ((Number) left).doubleValue() * ((Number) right).doubleValue() ); } else if( type == Float.class ) { result = new Float( ((Number) left).floatValue() * ((Number) right).floatValue() ); } else if( type == Long.class ) { result = new Long( ((Number) left).longValue() * ((Number) right).longValue() ); } else if( type == Integer.class ) { result = new Integer( ((Number) left).intValue() * ((Number) right).intValue() ); } else { throw new IllegalArgumentException( "Cannot evaluate '" + op + "'." ); } return result; } public Object visitAnnotationParenExpression( AnnotationParenExpression parenExpression ) { return parenExpression.getValue().accept( this ); } public Object visitAnnotationSubtract( AnnotationSubtract op ) { Object left = op.getLeft().accept( this ); Object right = op.getRight().accept( this ); Class type = resultType( left, right ); Object result; if( type == Double.class ) { result = new Double( ((Number) left).doubleValue() - ((Number) right).doubleValue() ); } else if( type == Float.class ) { result = new Float( ((Number) left).floatValue() - ((Number) right).floatValue() ); } else if( type == Long.class ) { result = new Long( ((Number) left).longValue() - ((Number) right).longValue() ); } else if( type == Integer.class ) { result = new Integer( ((Number) left).intValue() - ((Number) right).intValue() ); } else { throw new IllegalArgumentException( "Cannot evaluate '" + op + "'." ); } return result; } public Object visitAnnotationTypeRef( AnnotationTypeRef typeRef ) { JavaClass javaClass = typeRef.getType().getJavaClass(); return javaClass; } public Object visitAnnotationValueList( AnnotationValueList valueList ) { List list = new ArrayList(); for( ListIterator i = valueList.getValueList().listIterator(); i.hasNext(); ) { AnnotationValue value = (AnnotationValue) i.next(); Object v = value.accept( this ); list.add( v ); } return list; } public Object visitAnnotationAnd( AnnotationAnd and ) { Object left = and.getLeft().accept( this ); Object right = and.getRight().accept( this ); Class type = numericResultType( left, right ); Object result; if( type == Long.class ) { result = new Long( ((Number) left).longValue() & ((Number) right).longValue() ); } else if( type == Integer.class ) { result = new Integer( ((Number) left).intValue() & ((Number) right).intValue() ); } else { throw new IllegalArgumentException( "Cannot evaluate '" + and + "'." ); } return result; } public Object visitAnnotationGreaterEquals( AnnotationGreaterEquals greaterEquals ) { Object left = greaterEquals.getLeft().accept( this ); Object right = greaterEquals.getRight().accept( this ); Class type = resultType( left, right ); boolean result; if( type == Double.class ) { result = ((Number) left).doubleValue() >= ((Number) right).doubleValue(); } else if( type == Float.class ) { result = ((Number) left).floatValue() >= ((Number) right).floatValue(); } else if( type == Long.class ) { result = ((Number) left).longValue() >= ((Number) right).longValue(); } else if( type == Integer.class ) { result = ((Number) left).intValue() >= ((Number) right).intValue(); } else { throw new IllegalArgumentException( "Cannot evaluate '" + greaterEquals + "'." ); } return result ? Boolean.TRUE : Boolean.FALSE; } public Object visitAnnotationLessEquals( AnnotationLessEquals lessEquals ) { Object left = lessEquals.getLeft().accept( this ); Object right = lessEquals.getRight().accept( this ); Class type = resultType( left, right ); boolean result; if( type == Double.class ) { result = ((Number) left).doubleValue() <= ((Number) right).doubleValue(); } else if( type == Float.class ) { result = ((Number) left).floatValue() <= ((Number) right).floatValue(); } else if( type == Long.class ) { result = ((Number) left).longValue() <= ((Number) right).longValue(); } else if( type == Integer.class ) { result = ((Number) left).intValue() <= ((Number) right).intValue(); } else { throw new IllegalArgumentException( "Cannot evaluate '" + lessEquals + "'." ); } return result ? Boolean.TRUE : Boolean.FALSE; } public Object visitAnnotationLogicalAnd( AnnotationLogicalAnd and ) { Object left = and.getLeft().accept( this ); Object right = and.getRight().accept( this ); boolean result; if( left instanceof Boolean && right instanceof Boolean ) { result = ((Boolean) left).booleanValue() && ((Boolean) right).booleanValue(); } else { throw new IllegalArgumentException( "Cannot evaluate '" + and + "'." ); } return result ? Boolean.TRUE : Boolean.FALSE; } public Object visitAnnotationLogicalNot( AnnotationLogicalNot not ) { Object value = not.getValue().accept( this ); boolean result; if( value instanceof Boolean ) { result = !((Boolean) value).booleanValue(); } else { throw new IllegalArgumentException( "Cannot evaluate '" + not + "'." ); } return result ? Boolean.TRUE : Boolean.FALSE; } public Object visitAnnotationLogicalOr( AnnotationLogicalOr or ) { Object left = or.getLeft().accept( this ); Object right = or.getRight().accept( this ); boolean result; if( left instanceof Boolean && right instanceof Boolean ) { result = ((Boolean) left).booleanValue() || ((Boolean) right).booleanValue(); } else { throw new IllegalArgumentException( "Cannot evaluate '" + or + "'." ); } return result ? Boolean.TRUE : Boolean.FALSE; } public Object visitAnnotationMinusSign( AnnotationMinusSign sign ) { Object value = sign.getValue().accept( this ); Class type = unaryResultType( value ); Object result; if( type == Integer.class ) { result = new Integer( -((Integer) value).intValue() ); } else if( type == Long.class ) { result = new Long( -((Long) value).longValue() ); } else if( type == Float.class ) { result = new Float( -((Float) value).floatValue() ); } else if( type == Double.class ) { result = new Double( -((Double) value).intValue() ); } else { throw new IllegalArgumentException( "Cannot evaluate '" + sign + "'." ); } return result; } public Object visitAnnotationNot( AnnotationNot not ) { Object value = not.getValue().accept( this ); Object type = unaryNumericResultType( value ); Object result; if( type == Long.class ) { result = new Long( ~((Long) value).longValue() ); } else if( type == Integer.class ) { result = new Integer( ~((Integer) value).intValue() ); } else { throw new IllegalArgumentException( "Cannot evaluate '" + not + "'." ); } return result; } public Object visitAnnotationOr( AnnotationOr or ) { Object left = or.getLeft().accept( this ); Object right = or.getRight().accept( this ); Class type = numericResultType( left, right ); Object result; if( type == Long.class ) { result = new Long( ((Number) left).longValue() | ((Number) right).longValue() ); } else if( type == Integer.class ) { result = new Integer( ((Number) left).intValue() | ((Number) right).intValue() ); } else { throw new IllegalArgumentException( "Cannot evaluate '" + or + "'." ); } return result; } public Object visitAnnotationPlusSign( AnnotationPlusSign sign ) { Object value = sign.getValue().accept( this ); Object result; if( value instanceof Number ) { result = value; } else { throw new IllegalArgumentException( "Cannot evaluate '" + sign + "'." ); } return result; } public Object visitAnnotationRemainder( AnnotationRemainder remainder ) { Object left = remainder.getLeft().accept( this ); Object right = remainder.getRight().accept( this ); Class type = resultType( left, right ); Object result; if( type == Double.class ) { result = new Double( ((Number) left).doubleValue() % ((Number) right).doubleValue() ); } else if( type == Float.class ) { result = new Float( ((Number) left).floatValue() % ((Number) right).floatValue() ); } else if( type == Long.class ) { result = new Long( ((Number) left).longValue() % ((Number) right).longValue() ); } else if( type == Integer.class ) { result = new Integer( ((Number) left).intValue() % ((Number) right).intValue() ); } else { throw new IllegalArgumentException( "Cannot evaluate '" + remainder + "'." ); } return result; } public Object visitAnnotationShiftLeft( AnnotationShiftLeft shiftLeft ) { Object left = shiftLeft.getLeft().accept( this ); Object right = shiftLeft.getRight().accept( this ); Class type = numericResultType( left, right ); Object result; if( type == Long.class ) { result = new Long( ((Number) left).longValue() << ((Number) right).longValue() ); } else if( type == Integer.class ) { result = new Integer( ((Number) left).intValue() << ((Number) right).intValue() ); } else { throw new IllegalArgumentException( "Cannot evaluate '" + shiftLeft + "'." ); } return result; } public Object visitAnnotationShiftRight( AnnotationShiftRight shiftRight ) { Object left = shiftRight.getLeft().accept( this ); Object right = shiftRight.getRight().accept( this ); Class type = numericResultType( left, right ); Object result; if( type == Long.class ) { result = new Long( ((Number) left).longValue() >> ((Number) right).longValue() ); } else if( type == Integer.class ) { result = new Integer( ((Number) left).intValue() >> ((Number) right).intValue() ); } else { throw new IllegalArgumentException( "Cannot evaluate '" + shiftRight + "'." ); } return result; } public Object visitAnnotationUnsignedShiftRight( AnnotationUnsignedShiftRight shiftRight ) { Object left = shiftRight.getLeft().accept( this ); Object right = shiftRight.getRight().accept( this ); Class type = numericResultType( left, right ); Object result; if( type == Long.class ) { result = new Long( ((Number) left).longValue() >>> ((Number) right).longValue() ); } else if( type == Integer.class ) { result = new Integer( ((Number) left).intValue() >>> ((Number) right).intValue() ); } else { throw new IllegalArgumentException( "Cannot evaluate '" + shiftRight + "'." ); } return result; } public Object visitAnnotationEquals( AnnotationEquals annotationEquals ) { Object left = annotationEquals.getLeft().accept( this ); Object right = annotationEquals.getRight().accept( this ); Class type = resultType( left, right ); boolean result; if( type == Double.class ) { result = ((Number) left).doubleValue() == ((Number) right).doubleValue(); } else if( type == Float.class ) { result = ((Number) left).floatValue() == ((Number) right).floatValue(); } else if( type == Long.class ) { result = ((Number) left).longValue() == ((Number) right).longValue(); } else if( type == Integer.class ) { result = ((Number) left).intValue() == ((Number) right).intValue(); } else { result = (left == right); } return result ? Boolean.TRUE : Boolean.FALSE; } public Object visitAnnotationExclusiveOr( AnnotationExclusiveOr annotationExclusiveOr ) { Object left = annotationExclusiveOr.getLeft().accept( this ); Object right = annotationExclusiveOr.getRight().accept( this ); Class type = numericResultType( left, right ); Object result; if( type == Long.class ) { result = new Long( ((Number) left).longValue() ^ ((Number) right).longValue() ); } else if( type == Integer.class ) { result = new Integer( ((Number) left).intValue() ^ ((Number) right).intValue() ); } else { throw new IllegalArgumentException( "Cannot evaluate '" + annotationExclusiveOr + "'." ); } return result; } public Object visitAnnotationNotEquals( AnnotationNotEquals annotationNotEquals ) { Object left = annotationNotEquals.getLeft().accept( this ); Object right = annotationNotEquals.getRight().accept( this ); Class type = resultType( left, right ); boolean result; if( type == Double.class ) { result = ((Number) left).doubleValue() != ((Number) right).doubleValue(); } else if( type == Float.class ) { result = ((Number) left).floatValue() != ((Number) right).floatValue(); } else if( type == Long.class ) { result = ((Number) left).longValue() != ((Number) right).longValue(); } else if( type == Integer.class ) { result = ((Number) left).intValue() != ((Number) right).intValue(); } else { result = (left == right); } return result ? Boolean.TRUE : Boolean.FALSE; } public Object visitAnnotationQuery( AnnotationQuery annotationQuery ) { Object value = annotationQuery.getCondition().accept( this ); if( value == null || !(value instanceof Boolean) ) { throw new IllegalArgumentException( "Cannot evaluate '" + annotationQuery + "'." ); } AnnotationValue expression = ((Boolean) value).booleanValue() ? annotationQuery.getTrueExpression() : annotationQuery.getFalseExpression(); return expression.accept( this ); } public Object visitAnnotationCast( AnnotationCast annotationCast ) { Object value = annotationCast.getValue().accept( this ); String type = annotationCast.getType().getJavaClass().getFullyQualifiedName(); Object result; if( value instanceof Number ) { Number n = (Number) value; if( type.equals( "byte" ) ) { result = new Byte( n.byteValue() ); } else if( type.equals( "char" ) ) { result = new Character( (char) n.intValue() ); } else if( type.equals( "short" ) ) { result = new Short( n.shortValue() ); } else if( type.equals( "int" ) ) { result = new Integer( n.intValue() ); } else if( type.equals( "long" ) ) { result = new Long( n.longValue() ); } else if( type.equals( "float" ) ) { result = new Float( n.floatValue() ); } else if( type.equals( "double" ) ) { result = new Double( n.doubleValue() ); } else { throw new IllegalArgumentException( "Cannot evaluate '" + annotationCast + "'." ); } } else if( value instanceof String ) { if( type.equals( "java.lang.String" ) ) { result = value; } else { throw new IllegalArgumentException( "Cannot evaluate '" + annotationCast + "'." ); } } else { throw new IllegalArgumentException( "Cannot evaluate '" + annotationCast + "'." ); } return result; } } qdox-qdox-1.12.1/src/java/com/thoughtworks/qdox/model/annotation/RecursiveAnnotationVisitor.java000066400000000000000000000133411204551233600332330ustar00rootroot00000000000000package com.thoughtworks.qdox.model.annotation; import java.util.Iterator; import java.util.ListIterator; import com.thoughtworks.qdox.model.Annotation; public class RecursiveAnnotationVisitor implements AnnotationVisitor { public Object visitAnnotation( Annotation annotation ) { for( Iterator i = annotation.getPropertyMap().values().iterator(); i.hasNext(); ) { AnnotationValue value = (AnnotationValue) i.next(); value.accept( this ); } return null; } public Object visitAnnotationAdd( AnnotationAdd op ) { op.getLeft().accept( this ); op.getRight().accept( this ); return null; } public Object visitAnnotationConstant( AnnotationConstant constant ) { return null; } public Object visitAnnotationDivide( AnnotationDivide op ) { op.getLeft().accept( this ); op.getRight().accept( this ); return null; } public Object visitAnnotationFieldRef( AnnotationFieldRef fieldRef ) { return null; } public Object visitAnnotationGreaterThan( AnnotationGreaterThan op ) { op.getLeft().accept( this ); op.getRight().accept( this ); return null; } public Object visitAnnotationLessThan( AnnotationLessThan op ) { op.getLeft().accept( this ); op.getRight().accept( this ); return null; } public Object visitAnnotationMultiply( AnnotationMultiply op ) { op.getLeft().accept( this ); op.getRight().accept( this ); return null; } public Object visitAnnotationParenExpression( AnnotationParenExpression parenExpression ) { parenExpression.getValue().accept( this ); return null; } public Object visitAnnotationSubtract( AnnotationSubtract op ) { op.getLeft().accept( this ); op.getRight().accept( this ); return null; } public Object visitAnnotationTypeRef( AnnotationTypeRef typeRef ) { return null; } public Object visitAnnotationValueList( AnnotationValueList valueList ) { for( ListIterator i = valueList.getValueList().listIterator(); i.hasNext(); ) { AnnotationValue value = (AnnotationValue) i.next(); value.accept( this ); } return null; } public Object visitAnnotationAnd( AnnotationAnd and ) { and.getLeft().accept( this ); and.getRight().accept( this ); return null; } public Object visitAnnotationGreaterEquals( AnnotationGreaterEquals greaterEquals ) { greaterEquals.getLeft().accept( this ); greaterEquals.getRight().accept( this ); return null; } public Object visitAnnotationLessEquals( AnnotationLessEquals lessEquals ) { lessEquals.getLeft().accept( this ); lessEquals.getRight().accept( this ); return null; } public Object visitAnnotationLogicalAnd( AnnotationLogicalAnd and ) { and.getLeft().accept( this ); and.getRight().accept( this ); return null; } public Object visitAnnotationLogicalNot( AnnotationLogicalNot not ) { not.getValue().accept( this ); return null; } public Object visitAnnotationLogicalOr( AnnotationLogicalOr or ) { or.getLeft().accept( this ); or.getRight().accept( this ); return null; } public Object visitAnnotationMinusSign( AnnotationMinusSign sign ) { sign.getValue().accept( this ); return null; } public Object visitAnnotationNot( AnnotationNot not ) { not.getValue().accept( this ); return null; } public Object visitAnnotationOr( AnnotationOr or ) { or.getLeft().accept( this ); or.getRight().accept( this ); return null; } public Object visitAnnotationPlusSign( AnnotationPlusSign sign ) { sign.getValue().accept( this ); return null; } public Object visitAnnotationRemainder( AnnotationRemainder remainder ) { remainder.getLeft().accept( this ); remainder.getRight().accept( this ); return null; } public Object visitAnnotationShiftLeft( AnnotationShiftLeft left ) { left.getLeft().accept( this ); left.getRight().accept( this ); return null; } public Object visitAnnotationShiftRight( AnnotationShiftRight right ) { right.getLeft().accept( this ); right.getRight().accept( this ); return null; } public Object visitAnnotationUnsignedShiftRight( AnnotationUnsignedShiftRight right ) { right.getLeft().accept( this ); right.getRight().accept( this ); return null; } public Object visitAnnotationEquals( AnnotationEquals annotationEquals ) { annotationEquals.getLeft().accept( this ); annotationEquals.getRight().accept( this ); return null; } public Object visitAnnotationExclusiveOr( AnnotationExclusiveOr annotationExclusiveOr ) { annotationExclusiveOr.getLeft().accept( this ); annotationExclusiveOr.getRight().accept( this ); return null; } public Object visitAnnotationNotEquals( AnnotationNotEquals annotationNotEquals ) { annotationNotEquals.getLeft().accept( this ); annotationNotEquals.getRight().accept( this ); return null; } public Object visitAnnotationQuery( AnnotationQuery annotationQuery ) { annotationQuery.getCondition().accept( this ); annotationQuery.getTrueExpression().accept( this ); annotationQuery.getFalseExpression().accept( this ); return null; } public Object visitAnnotationCast( AnnotationCast annotationCast ) { annotationCast.getValue().accept( this ); return null; } } qdox-qdox-1.12.1/src/java/com/thoughtworks/qdox/model/util/000077500000000000000000000000001204551233600236075ustar00rootroot00000000000000qdox-qdox-1.12.1/src/java/com/thoughtworks/qdox/model/util/OrderedMap.java000066400000000000000000000060161204551233600264770ustar00rootroot00000000000000package com.thoughtworks.qdox.model.util; import java.util.AbstractMap; import java.util.AbstractSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; /** * This is a simple Map implementation backed by a List of Map.Entry objects. * It has the property that iterators return entries in the order in whick * they were inserted. * * Operations involving searching, including get() and put(), have cost linear * to the size of the map. In other words, avoid this implementation if your * Map might get large. * * If we could assume Java 1.4+, we'd just use java.util.LinkedHashMap * instead of this class. But we can't. * * @author Mike Williams */ public class OrderedMap extends AbstractMap { private Set _entrySet = new OrderedSet(); public Set entrySet() { return _entrySet; } public Object put(Object key, Object value) { Entry existingEntry = getEntryWithKey(key); if (existingEntry == null) { entrySet().add(new Entry(key, value)); return null; } Object previousValue = existingEntry.getValue(); existingEntry.setValue(value); return previousValue; } private Entry getEntryWithKey(Object key) { Iterator i = entrySet().iterator(); while (i.hasNext()) { Entry e = (Entry) i.next(); if (eq(e.getKey(), key)) { return e; } } return null; } static class OrderedSet extends AbstractSet { private List _elementList = new LinkedList(); public int size() { return _elementList.size(); } public Iterator iterator() { return _elementList.iterator(); } public boolean add(Object o) { _elementList.add(o); return true; } } static class Entry implements Map.Entry { Object _key; Object _value; public Entry(Object key, Object value) { _key = key; _value = value; } public Object getKey() { return _key; } public Object getValue() { return _value; } public Object setValue(Object value) { Object oldValue = _value; _value = value; return oldValue; } public boolean equals(Object o) { if (!(o instanceof Map.Entry)) { return false; } Map.Entry e = (Map.Entry) o; return eq(_key, e.getKey()) && eq(_value, e.getValue()); } public int hashCode() { return ((_key == null) ? 0 : _key.hashCode()) ^ ((_value == null) ? 0 : _value.hashCode()); } public String toString() { return _key + "=" + _value; } } private static boolean eq(Object o1, Object o2) { return (o1 == null ? o2 == null : o1.equals(o2)); } }qdox-qdox-1.12.1/src/java/com/thoughtworks/qdox/model/util/TagParser.java000066400000000000000000000103431204551233600263430ustar00rootroot00000000000000package com.thoughtworks.qdox.model.util; import java.io.IOException; import java.io.StreamTokenizer; import java.io.StringReader; import java.util.ArrayList; import java.util.Map; public class TagParser { /** * Create a StreamTokenizer suitable for parsing the tag text. */ static StreamTokenizer makeTokenizer(String tagValue) { StreamTokenizer tokenizer = new StreamTokenizer(new StringReader(tagValue)); tokenizer.resetSyntax(); tokenizer.wordChars('A','Z'); tokenizer.wordChars('a','z'); tokenizer.wordChars('0','9'); tokenizer.wordChars('-','-'); tokenizer.wordChars('_','_'); tokenizer.wordChars('.','.'); tokenizer.wordChars('<','<'); tokenizer.wordChars('>','>'); tokenizer.quoteChar('\''); tokenizer.quoteChar('"'); tokenizer.whitespaceChars(' ',' '); tokenizer.whitespaceChars('\t','\t'); tokenizer.whitespaceChars('\n','\n'); tokenizer.whitespaceChars('\r','\r'); tokenizer.eolIsSignificant(false); return tokenizer; } /** * Extract a Map of named parameters */ public static Map parseNamedParameters(String tagValue) { Map paramMap = new OrderedMap(); StreamTokenizer tokenizer = makeTokenizer(tagValue); try { while (tokenizer.nextToken() == StreamTokenizer.TT_WORD) { String key = tokenizer.sval; if (tokenizer.nextToken() != '=') { break; } switch (tokenizer.nextToken()) { case StreamTokenizer.TT_WORD: case '"': case '\'': paramMap.put(key, tokenizer.sval); default: break; } } } catch (IOException e) { // ignore } return paramMap; } /** * Extract an array of positional parameters */ public static String[] parseWords(String tagValue) { StreamTokenizer tokenizer = makeTokenizer(tagValue); ArrayList wordList = new ArrayList(); try { while (tokenizer.nextToken() != StreamTokenizer.TT_EOF) { if (tokenizer.sval == null) { wordList.add(Character.toString((char)tokenizer.ttype)); } else { wordList.add(tokenizer.sval); } } } catch (IOException e) { e.printStackTrace(); throw new RuntimeException("error tokenizing tag"); } String[] wordArray = new String[wordList.size()]; wordList.toArray(wordArray); return wordArray; } /** * Extract an array of parameters as name or name=value representation * @since 1.11 */ public static String[] parseParameters(String tagValue) { StreamTokenizer tokenizer = makeTokenizer(tagValue); ArrayList wordList = new ArrayList(); try { while (tokenizer.nextToken() != StreamTokenizer.TT_EOF) { StringBuilder param = new StringBuilder(); if (tokenizer.sval != null) { param.append( tokenizer.sval ); } //check for parameterValues while (tokenizer.nextToken() != StreamTokenizer.TT_EOF) { if(tokenizer.sval == null && ('=' == (char)tokenizer.ttype || ','== (char)tokenizer.ttype)){ param.append( Character.toString( (char)tokenizer.ttype ) ); //file was parsed correctly, so this works. tokenizer.nextToken(); param.append(tokenizer.sval); } else { tokenizer.pushBack(); break; } } wordList.add(param.toString()); } } catch (IOException e) { e.printStackTrace(); throw new RuntimeException("error tokenizing tag"); } String[] wordArray = new String[wordList.size()]; wordList.toArray(wordArray); return wordArray; } } qdox-qdox-1.12.1/src/java/com/thoughtworks/qdox/parser/000077500000000000000000000000001204551233600230265ustar00rootroot00000000000000qdox-qdox-1.12.1/src/java/com/thoughtworks/qdox/parser/Builder.java000066400000000000000000000017621204551233600252650ustar00rootroot00000000000000package com.thoughtworks.qdox.parser; import com.thoughtworks.qdox.model.Annotation; import com.thoughtworks.qdox.model.Type; import com.thoughtworks.qdox.parser.structs.ClassDef; import com.thoughtworks.qdox.parser.structs.FieldDef; import com.thoughtworks.qdox.parser.structs.MethodDef; import com.thoughtworks.qdox.parser.structs.PackageDef; import com.thoughtworks.qdox.parser.structs.TagDef; import com.thoughtworks.qdox.parser.structs.TypeDef; public interface Builder { void addPackage(PackageDef packageDef); void addImport(String importName); void addJavaDoc(String text); void addJavaDocTag(TagDef def); void beginClass(ClassDef def); void endClass(); void beginMethod(); void endMethod(MethodDef def); void addParameter(FieldDef def); void addField(FieldDef def); void addAnnotation(Annotation annotation); /** * @deprecated */ Type createType(String name, int dimensions); Type createType(TypeDef name); } qdox-qdox-1.12.1/src/java/com/thoughtworks/qdox/parser/Lexer.java000066400000000000000000000003441204551233600247510ustar00rootroot00000000000000package com.thoughtworks.qdox.parser; import java.io.IOException; public interface Lexer { int lex() throws IOException; String text(); int getLine(); int getColumn(); String getCodeBody(); } qdox-qdox-1.12.1/src/java/com/thoughtworks/qdox/parser/ParseException.java000066400000000000000000000013041204551233600266200ustar00rootroot00000000000000package com.thoughtworks.qdox.parser; /** * Thrown to indicate an error during parsing */ public class ParseException extends RuntimeException { private int line; private int column; private String errorMessage; public ParseException(String message, int line, int column) { errorMessage = message + " @[" + line + "," + column + "] in "; this.line = line; this.column = column; } public int getLine() { return line; } public int getColumn() { return column; } public void setSourceInfo(String sourceInfo) { errorMessage += sourceInfo; } public String getMessage() { return errorMessage; } } qdox-qdox-1.12.1/src/java/com/thoughtworks/qdox/parser/structs/000077500000000000000000000000001204551233600245355ustar00rootroot00000000000000qdox-qdox-1.12.1/src/java/com/thoughtworks/qdox/parser/structs/AnnoDef.java000066400000000000000000000017451204551233600267210ustar00rootroot00000000000000package com.thoughtworks.qdox.parser.structs; import java.util.HashMap; import java.util.Iterator; import java.util.Map; public class AnnoDef extends LocatedDef { public String name = ""; public Map args = new HashMap(); public AnnoDef tempAnno = null; // holds an annotation to construct nested values public boolean equals(Object obj) { AnnoDef annoDef = (AnnoDef) obj; return annoDef.name.equals(name) && annoDef.args.equals(args); } public int hashCode() { return name.hashCode() + args.hashCode(); } public String toString() { StringBuffer result = new StringBuffer(); result.append('@'); result.append(name); result.append('('); if( !args.isEmpty() ) { for(Iterator i = args.entrySet().iterator(); i.hasNext();) result.append( i.next() + ","); result.deleteCharAt( result.length()-1 ); } result.append(')'); return result.toString(); } } qdox-qdox-1.12.1/src/java/com/thoughtworks/qdox/parser/structs/ClassDef.java000066400000000000000000000032551204551233600270710ustar00rootroot00000000000000package com.thoughtworks.qdox.parser.structs; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; public class ClassDef extends LocatedDef { public static final String CLASS = "class"; public static final String INTERFACE = "interface"; public static final String ENUM = "enum"; public static final String ANNOTATION_TYPE = "@interface"; public String name = ""; public Set modifiers = new HashSet(); public List typeParams = new ArrayList(); // public Set extendz = new HashSet(); public Set implementz = new HashSet(); public String type = CLASS; public boolean equals(Object obj) { ClassDef classDef = (ClassDef) obj; return classDef.name.equals(name) && classDef.type == type && classDef.typeParams.equals( typeParams ) && classDef.modifiers.equals(modifiers) && classDef.extendz.equals(extendz) && classDef.implementz.equals(implementz); } public int hashCode() { return name.hashCode() + type.hashCode() + typeParams.hashCode()+ modifiers.hashCode() + extendz.hashCode() + implementz.hashCode(); } public String toString() { StringBuffer result = new StringBuffer(); result.append(modifiers); result.append(" "); result.append(type); result.append(" "); result.append(name); //typeParams result.append(" extends "); result.append(extendz); result.append(" implements "); result.append(implementz); return result.toString(); } } qdox-qdox-1.12.1/src/java/com/thoughtworks/qdox/parser/structs/FieldDef.java000066400000000000000000000032431204551233600270440ustar00rootroot00000000000000package com.thoughtworks.qdox.parser.structs; import java.util.HashSet; import java.util.Set; public class FieldDef extends LocatedDef { public String name = ""; public TypeDef type; public Set modifiers = new HashSet(); public int dimensions; public boolean isVarArgs; public String body = ""; public boolean equals(Object obj) { FieldDef paramDef = (FieldDef) obj; boolean result = paramDef.name.equals(name) && paramDef.modifiers.equals(modifiers) && paramDef.isVarArgs == isVarArgs; if(paramDef.type == null) { result &= (type == null) && paramDef.dimensions == dimensions; } else { result &= (type != null) &&(paramDef.type.name.equals(type.name)) &&(paramDef.type.actualArgumentTypes == null ? type.actualArgumentTypes == null: paramDef.type.actualArgumentTypes.equals(type.actualArgumentTypes)) &&(paramDef.type.dimensions + paramDef.dimensions == dimensions + type.dimensions); } return result; } public int hashCode() { return name.hashCode() + (type != null ? type.hashCode() : 0) + dimensions + modifiers.hashCode() + (isVarArgs ? 79769989 : 0); } public String toString() { StringBuffer result = new StringBuffer(); result.append(modifiers); result.append(' '); result.append(type); for (int i = 0; i < dimensions; i++) result.append("[]"); result.append(' '); result.append(name); if(body.length() > 0){ result.append(" = ").append(body); } return result.toString(); } } qdox-qdox-1.12.1/src/java/com/thoughtworks/qdox/parser/structs/LocatedDef.java000066400000000000000000000001461204551233600273730ustar00rootroot00000000000000package com.thoughtworks.qdox.parser.structs; public class LocatedDef { public int lineNumber; } qdox-qdox-1.12.1/src/java/com/thoughtworks/qdox/parser/structs/MethodDef.java000066400000000000000000000045661204551233600272520ustar00rootroot00000000000000package com.thoughtworks.qdox.parser.structs; import java.util.ArrayList; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; public class MethodDef extends LocatedDef { public String name = ""; public List typeParams; // public TypeDef returnType; public Set modifiers = new HashSet(); public List params = new ArrayList(); public Set exceptions = new LinkedHashSet(); public boolean constructor = false; public int dimensions; public String body; public boolean equals(Object obj) { MethodDef methodDef = (MethodDef) obj; boolean result; result = methodDef.name.equals(name) && methodDef.modifiers.equals(modifiers) && methodDef.params.equals(params) && methodDef.exceptions.equals(exceptions) && methodDef.constructor == constructor; if(methodDef.returnType == null) { result &= (returnType == null) && methodDef.dimensions == dimensions; } else { result &= (returnType != null) &&(methodDef.returnType.name.equals(returnType.name)) &&(methodDef.returnType.actualArgumentTypes == null ? returnType.actualArgumentTypes == null: methodDef.returnType.actualArgumentTypes.equals(returnType.actualArgumentTypes)) &&(methodDef.returnType.dimensions + methodDef.dimensions == dimensions + returnType.dimensions); } return result; } public int hashCode() { return name.hashCode() + (returnType != null ? returnType.hashCode() : 0) + modifiers.hashCode() + params.hashCode() + params.hashCode() + exceptions.hashCode() + dimensions + (constructor ? 0 : 1); } public String toString() { StringBuffer result = new StringBuffer(); result.append(modifiers); result.append(' '); result.append((returnType != null ? returnType.toString() : "")); for (int i = 0; i < dimensions; i++) result.append("[]"); result.append(' '); result.append(name); result.append('('); result.append(params); result.append(')'); result.append(" throws "); result.append(exceptions); result.append(body); return result.toString(); } } qdox-qdox-1.12.1/src/java/com/thoughtworks/qdox/parser/structs/PackageDef.java000066400000000000000000000006601204551233600273540ustar00rootroot00000000000000package com.thoughtworks.qdox.parser.structs; public class PackageDef extends LocatedDef { public String name = ""; public PackageDef(String name) { this.name = name; } public PackageDef(String name, int lineNumber) { this.name = name; this.lineNumber = lineNumber; } public boolean equals(Object obj) { PackageDef packageDef = (PackageDef) obj; return packageDef.name.equals(name); } } qdox-qdox-1.12.1/src/java/com/thoughtworks/qdox/parser/structs/TagDef.java000066400000000000000000000017761204551233600265450ustar00rootroot00000000000000package com.thoughtworks.qdox.parser.structs; public class TagDef extends LocatedDef { public String name; public String text; public TagDef(String name, String text, int lineNumber) { this.name = name; this.text = text; this.lineNumber = lineNumber; } public TagDef(String name, String text) { this(name, text, -1); } public boolean equals(Object obj) { TagDef tagDef = (TagDef) obj; return tagDef.name.equals(name) && tagDef.text.equals(text) && tagDef.lineNumber == lineNumber; } public int hashCode() { return name.hashCode() + text.hashCode() + lineNumber; } public String toString() { StringBuffer result = new StringBuffer(); result.append('@'); result.append(name); result.append(" => \""); result.append(text); result.append("\" @ line "); result.append(lineNumber); return result.toString(); } } qdox-qdox-1.12.1/src/java/com/thoughtworks/qdox/parser/structs/TypeDef.java000066400000000000000000000015051204551233600267410ustar00rootroot00000000000000package com.thoughtworks.qdox.parser.structs; import java.util.List; public class TypeDef { public String name; public int dimensions; public List actualArgumentTypes; public TypeDef(String name, int dimensions) { this.name = name; this.dimensions = dimensions; } public TypeDef(String name) { this(name, 0); } public boolean equals(Object obj) { TypeDef typeDef = (TypeDef) obj; return typeDef.name.equals(name) && typeDef.dimensions == dimensions && (typeDef.actualArgumentTypes != null ? typeDef.actualArgumentTypes.equals(actualArgumentTypes): actualArgumentTypes == null); } public int hashCode() { return name.hashCode() + dimensions + (actualArgumentTypes == null ? 0 : actualArgumentTypes.hashCode()); } } qdox-qdox-1.12.1/src/java/com/thoughtworks/qdox/parser/structs/TypeVariableDef.java000066400000000000000000000005301204551233600304040ustar00rootroot00000000000000package com.thoughtworks.qdox.parser.structs; import java.util.List; public class TypeVariableDef { public String name; public List bounds; public TypeVariableDef(String name) { this.name = name; } public TypeVariableDef(String name, List bounds) { super(); this.name = name; this.bounds = bounds; } }qdox-qdox-1.12.1/src/java/com/thoughtworks/qdox/parser/structs/WildcardTypeDef.java000066400000000000000000000015641204551233600304200ustar00rootroot00000000000000package com.thoughtworks.qdox.parser.structs; /** * WildcardTypeDef must be a subclass of TypeDef, so it can be used in other classes. * But here are only 2 fields interesting: typeDef and wildcardExpressionType * typeDef itself can be generic, so it must be resolvable * wildcardExpressionType is super or extends * * * @author Robert Scholte * */ public class WildcardTypeDef extends TypeDef { private TypeDef typeDef; private String wildcardExpressionType; //super or extends public WildcardTypeDef() { super("?"); } public WildcardTypeDef(TypeDef typeDef, String wildcardExpressionType) { super(typeDef.name, typeDef.dimensions); this.typeDef = typeDef; this.wildcardExpressionType = wildcardExpressionType; } public TypeDef getTypeDef() { return typeDef; } public String getWildcardExpressionType() { return wildcardExpressionType; } } qdox-qdox-1.12.1/src/java/com/thoughtworks/qdox/tools/000077500000000000000000000000001204551233600226725ustar00rootroot00000000000000qdox-qdox-1.12.1/src/java/com/thoughtworks/qdox/tools/QDoxTester.java000066400000000000000000000130101204551233600255720ustar00rootroot00000000000000package com.thoughtworks.qdox.tools; import com.thoughtworks.qdox.JavaDocBuilder; import com.thoughtworks.qdox.directorywalker.DirectoryScanner; import com.thoughtworks.qdox.directorywalker.FileVisitor; import com.thoughtworks.qdox.directorywalker.SuffixFilter; import com.thoughtworks.qdox.parser.ParseException; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintStream; import java.util.Enumeration; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; /** * Tool for testing that QDox can parse Java source code. * * @author Joe Walnes */ public class QDoxTester { public static interface Reporter { void success(String id); void parseFailure(String id, int line, int column, String reason); void error(String id, Throwable throwable); } private final Reporter reporter; public QDoxTester(Reporter reporter) { this.reporter = reporter; } public void checkZipOrJarFile(File file) throws IOException { ZipFile zipFile = new ZipFile(file); Enumeration entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry zipEntry = (ZipEntry) entries.nextElement(); InputStream inputStream = zipFile.getInputStream(zipEntry); try { verify(file.getName() + "!" + zipEntry.getName(), inputStream); } finally { inputStream.close(); } } } public void checkDirectory(File dir) throws IOException { DirectoryScanner directoryScanner = new DirectoryScanner(dir); directoryScanner.addFilter(new SuffixFilter(".java")); directoryScanner.scan(new FileVisitor() { public void visitFile(File file) { try { checkJavaFile(file); } catch (IOException e) { // ? } } }); } public void checkJavaFile(File file) throws IOException { InputStream inputStream = new FileInputStream(file); try { verify(file.getName(), inputStream); } finally { inputStream.close(); } } private void verify(String id, InputStream inputStream) { try { JavaDocBuilder javaDocBuilder = new JavaDocBuilder(); javaDocBuilder.addSource(new BufferedReader(new InputStreamReader(inputStream))); reporter.success(id); } catch (ParseException parseException) { reporter.parseFailure(id, parseException.getLine(), parseException.getColumn(), parseException.getMessage()); } catch (Exception otherException) { reporter.error(id, otherException); } } public static void main(String[] args) throws IOException { if (args.length == 0) { System.err.println("Tool that verifies that QDox can parse some Java source."); System.err.println(); System.err.println("Usage: java " + QDoxTester.class.getName() + " src1 [src2] [src3]..."); System.err.println(); System.err.println("Each src can be a single .java file, or a directory/zip/jar containing multiple source files"); System.exit(-1); } ConsoleReporter reporter = new ConsoleReporter(System.out); QDoxTester qDoxTester = new QDoxTester(reporter); for (int i = 0; i < args.length; i++) { File file = new File(args[i]); if (file.isDirectory()) { qDoxTester.checkDirectory(file); } else if (file.getName().endsWith(".java")) { qDoxTester.checkJavaFile(file); } else if (file.getName().endsWith(".jar") || file.getName().endsWith(".zip")) { qDoxTester.checkZipOrJarFile(file); } else { System.err.println("Unknown input <" + file.getName() + ">. Should be zip, jar, java or directory"); } } reporter.writeSummary(); } private static class ConsoleReporter implements Reporter { private final PrintStream out; private int success; private int failure; private int error; private int dotsWrittenThisLine; public ConsoleReporter(PrintStream out) { this.out = out; } public void success(String id) { success++; if (++dotsWrittenThisLine > 80) { newLine(); } out.print('.'); } private void newLine() { dotsWrittenThisLine = 0; out.println(); out.flush(); } public void parseFailure(String id, int line, int column, String reason) { newLine(); out.println("* " + id); out.println(" [" + line + ":" + column + "] " + reason); failure++; } public void error(String id, Throwable throwable) { newLine(); out.println("* " + id); throwable.printStackTrace(out); error++; } public void writeSummary() { newLine(); out.println("-- Summary --------------"); out.println("Success: " + success); out.println("Failure: " + failure); out.println("Error : " + error); out.println("Total : " + (success + failure + error)); out.println("-------------------------"); } } } qdox-qdox-1.12.1/src/site/000077500000000000000000000000001204551233600152545ustar00rootroot00000000000000qdox-qdox-1.12.1/src/site/content/000077500000000000000000000000001204551233600167265ustar00rootroot00000000000000qdox-qdox-1.12.1/src/site/content/changes.html000066400000000000000000000006271204551233600212310ustar00rootroot00000000000000 Jira Change History

Full details can be found in Jira's Roadmap and Change Log.

qdox-qdox-1.12.1/src/site/content/download.html000066400000000000000000000031141204551233600214220ustar00rootroot00000000000000 Download

Latest stable release - QDox ${project.rel.org.thoughtworks.qdox:qdox}: binary jar | sources jar | javadoc jar | project tar.bz2 | project tar.gz | project zip

The latest snapshot - QDox ${project.dev.org.thoughtworks.qdox:qdox}: snapshots directory.

qdox-qdox-1.12.1/src/site/content/faq.html000066400000000000000000000052261204551233600203700ustar00rootroot00000000000000 Frequently Asked Questions

Where is the array information stored?

The Type class stores array information in it. If the array is multidimensional, the dimension depth can be accessed.

What's the object type of an interface?

The JavaClass method is used to represent both classes and interfaces. The isInterface() method allows you to distinguish between the two.

When using a class, the getSuperClass() return which class is extended. If this has not been defined in the input source code, java.lang.Object is returned. When using an interface, this method ALWAYS returns null.

When using a class, the getImplements() returns an array of the interfaces implemented by the class. If none are implemented, an empty array is returned. When using an interface, this returns an array of interfaces the current interface EXTENDS.

Can I have full control over the classloader?

I some cases QDox is used to generate classes for another project with it's own dependencies. This could result in class-collission. By default the JavadocBuilder will contain the classloader(s) of the current project, but by defining your own classLibrary you can have the required control.

    /* new ClassLibrary() will give you an empty classLoader
     * Big chance you want at least the system classloader.
     */	
    ClassLibrary classLibrary = new ClassLibrary( ClassLoader.getSystemClassLoader() );
    JavaDocBuilder builder = new JavaDocBuilder(classLibrary);
    
      

qdox-qdox-1.12.1/src/site/content/index.html000066400000000000000000000023721204551233600207270ustar00rootroot00000000000000 Overview

QDox

QDox is a high speed, small footprint parser for extracting class/interface/method definitions from source files complete with JavaDoc @tags. It is designed to be used by active code generators or documentation tools.

In A Nutshell

A custom built parser has been built using JFlex and BYacc/J. These have been chosen because of their proven performance and they require no external libraries at runtime.

The parser skims the source files only looking for things of interest such as class/interface definitions, import statements, JavaDoc and member declarations. The parser ignores things such as actual method implementations to avoid overhead (while in method blocks, curly brace counting suffices).

The end result of the parser is a very simple document model containing enough information to be useful.

Getting Started

  1. Download it.
  2. Use it.

qdox-qdox-1.12.1/src/site/content/license.html000066400000000000000000000015631204551233600212430ustar00rootroot00000000000000 The License

Copyright 2002-2009 Joe Walnes and QDox Project Team

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.

qdox-qdox-1.12.1/src/site/content/model.html000066400000000000000000000444651204551233600207310ustar00rootroot00000000000000 The Model

After the source code has been parsed, the content of the files can be navigated using a simple to use and intuitive object model.

JavaSource

Represents a complete .java file. This contains a collection of classes.

Example Input

    package com.blah.foo;
    
    import java.awt.*;
    import java.util.List;
    
    public class Class1 {
      ...
    }
    
    class Class2 {
    }
    
    interface Interface1 {
    }
            

Example Code

    JavaDocBuilder builder = new JavaDocBuilder();
    builder.addSource(myReader);
    
    JavaSource src = builder.getSources[](0);
    
    JavaPackage pkg      = src.getPackage(); 
    String[] imports     = src.getImports(); // {"java.awt.*",
                                         //  "java.util.List"}
    
    JavaClass class1     = src.getClasses()[0];
    JavaClass class2     = src.getClasses()[1];
    JavaClass interface1 = src.getClasses()[2];
            

JavaPackage

Represents the package of the class.

Example input

    package com.blah.foo;
    
    public class BarClass  {
    ...
    }
            

Example Code

    JavaDocBuilder builder = new JavaDocBuilder();
    builder.addSource(myReader);
    
    JavaSource src = builder.getSources[](0);
    
    JavaPackage pkg      = src.getPackage();
    
    JavaClass[] classes  = pkg.getClasses()[0]; // BarClass
    String name          = pkg.getName(); // "com.blah.foo"
    String toString      = pkg.toString(); // "package com.blah.foo" conform javaAPI
    JavaPackage parent   = pkg.getParentPackage(); //
            

JavaClass

Represents a class or interface. This contains doclet tags, fields and methods. Information about the class definition is available, such as which classes are extended, which interfaces implemented and modifiers.

Example Input

    package com.blah.foo;
    
    import java.io.*;
    import com.custom.*;
    import com.base.SubClass;
    
    /**
     * @author Joe
     */
    public abstract class MyClass extends SubClass
                implements Serializable, CustomInterface  {
    
      private String name;
      public void doStuff() { ... }
      private int getNumber() { ... }
    
    }
            

Example Code

    JavaDocBuilder builder = new JavaDocBuilder();
    builder.addSource(myReader);
    
    JavaClass cls = builder.getClassByName("com.blah.foo.MyClass");
    
    String pkg      = cls.getPackage();            // "com.blah.foo"
    String name     = cls.getName();               // "MyClass"
    String fullName = cls.getFullyQualifiedName(); // "com.blah.foo.MyClass";
    boolean isInterface = cls.isInterface();       // false
    
    boolean isPublic   = cls.isPublic();   // true
    boolean isAbstract = cls.isAbstract(); // true
    boolean isFinal    = cls.isFinal();    // false
    
    Type superClass = cls.getSuperClass(); // "com.base.SubClass";
    Type[] imps     = cls.getImplements(); // {"java.io.Serializable",
                                           //  "com.custom.CustomInterface"}
    
    String author = cls.getTagsByName("author").getValue(); // "joe"
    
    JavaField nameField = cls.getFields()[0];
    JavaMethod doStuff = cls.getMethods()[0];
    JavaMethod getNumber = cls.getMethods()[1];
    
    JavaSource javaSource = cls.getParentSource();
            

JavaField

Represents a field in a class. This has doclet tags, a name and a type.

Example Input

    import java.util.Date;
    
    public class MyClass  {
    
      /**
       * @magic
       */
      private String email;
    
      public static Date[][] dates;
    
    }
            

Example Code

    JavaField e = cls.getFields()[0];
    
    Type eType     = e.getType(); // "java.lang.String";
    String eName   = e.getName(); // "email";
    DocletTag eTag = e.getTagsByName("magic"); // @magic
    boolean eArray = e.getType().isArray(); // false;
    
    JavaField d = cls.getFields()[1];
    
    Type dType     = d.getType(); // "java.util.Date";
    String dName   = d.getName(); // "dates";
    DocletTag dTag = d.getTagsByName("magic"); // null
    boolean dArray = d.getType().isArray(); // true;
    int dDimensions= d.getType().getDimensions(); // 2;
    boolean dStatic= d.isStatic(); // true;
    
    JavaClass javaClass = d.getParentClass();
            

JavaMethod

Represents a method in a class. This has doclet tags, a name, return type, parameters and exceptions.

Example Input

    import java.util.Date;
    import java.io.*;
    
    public class MyClass  {
    
      /**
       * @returns Lots of dates
       */
      public static Date[] doStuff(int number,
                                   String stuff)
                throws RuntimeException, IOException {
        ...
      }
    
    }
            

Example Code

    JavaMethod m = cls.getMethods()[0];
    
    String mName = m.getName(); // "doStuff";
    Type mReturns = m.getReturns(); // "java.util.Date";
    boolean mArray = m.getReturns().isArray(); // true
    boolean mStatic = m.isStatic(); // true
    boolean mPublic = m.isPublic(); // true
    
    String doc = m.getTagByName("returns").getValue();
      // "Lots of dates"
    
    Type[] exceptions = m.getExceptions();
      // {"java.lang.RuntimeException", "java.io.IOException"}
    
    JavaParameter numberParam = m.getParameters()[0];
    JavaParameter stuffParam = m.getParameters()[1];
    
    JavaClass javaClass = m.getParentClass();
            

JavaParameter

Represents a parameter passed to a method. This has a name and a type.

Example Input

    public class MyClass  {
    
      public void stuff(int n, Object[] objects) {
        ...
      }
    
    }
            

Example Code

    JavaMethod m = cls.getMethods()[0];
    
    JavaParameter n = m.getParameters()[0];
    String nName = n.getName(); // "n"
    Type nType   = n.getType(); // "int";
    
    JavaParameter o = m.getParameters()[1];
    String oName   = o.getName(); // "objects"
    Type oType     = o.getType(); // "java.lang.Object";
    boolean oArray = o.getType().isArray(); // true
    
    JavaMethod javaMethod = o.getParentMethod();
            

Type

Represents a specific instance of a class used by another class (such as return value, superclass, etc). The value represents the name of the class. Array dimensions are also available. Since 1.8 it's also possible to get the generic value of the Type

Example Input

    import java.util.*;
    
    public class MyClass  {
    
      public void stuff(int n, Object[] objects,
    	                  Date[][] dates, List stringList) {
        ...
      }
    
    }
            

Example Code

    JavaMethod m = cls.getMethods()[0];
    
    Type returns = m.getReturns();
    returns.getValue(); // "void"
    returns.isArray(); // false
    returns.getDimensions(); // 0
    
    Type n = m.getParameters()[0].getType();
    n.getValue(); // "int"
    n.isArray(); // false
    n.getDimensions(); // 0
    
    Type objects = m.getParameters()[1].getType();
    objects.getValue(); // "java.lang.Object"
    objects.isArray(); // true
    objects.getDimensions(); // 1
    
    Type dates = m.getParameters()[2].getType();
    dates.getValue(); // "java.util.Date"
    dates.isArray(); // true
    dates.getDimensions(); // 2
    
    Type stringList = m.getParameters()[3].getType();
    stringList.getValue(); // "java.util.List"
    stringList.getGenericValue(); // "java.util.List"
    stringList.isArray(); // false
    stringList.getDimensions(); // 0
          

DocletTag

Represents a JavaDoc tag. Each tag has a name and a value. Optionally, the value can be broken up into tokens accessed by index or name.

The JavaClass, JavaField and JavaMethod classes all support comments and DocletTags

The returned DocletTag carries the name, value and methods for breaking up the value into specific parameters.

Example Input

    /**
     * This method does nothing at all.
     *
     * @returns A boolean of whether we care or not.
     * @param email Someone's email address.
     * @param dob Date of birth.
     *
     * @permission administrator full-access
     * @webservice publish=true name=myservice type=rpc
     */
    boolean doWeCare(String email, Date dob);
            

Example Code

    JavaMethod mth = cls.getMethods()[0];
    
    // Access the JavaDoc comment
    String comment = mth.getComment();
      // "This method does nothing at all."
    
    // Access a single doclet tag
    DocletTag returns = mth.getTagByName("returns");
    returns.getName(); // "returns";
    returns.getValue(); // "A boolean of whether we care or not."
    
    // Access multiple doclet tags with the same name
    DocletTag[] params = mth.getTagsByName("param");
    params[0].getValue(); // "Someone's email address."
    params[1].getValue(); // "Date of birth."
    
    // Access specific parameters of a doclet tag by index
    DocletTag permission = mth.getTagByName("permission");
    permission.getParameter[0]; // "administrator"
    permission.getParameter[1]; // "full-access"
    
    // Access specific parameters of a doclet tag by name
    DocletTag webservice = mth.getTagByName("webservice");
    webservice.getNamedParameter("type"); // "rpc"
    webservice.getNamedParameter("name"); // "myservice"
           
qdox-qdox-1.12.1/src/site/content/upgrade.html000066400000000000000000000132571204551233600212530ustar00rootroot00000000000000 Upgrading

Upgrading to 1.10.1 or above

This section describes what needs to be done when upgrading to QDox 1.10.1.

Things that might break your code

In some cases the Type.toString() was inconsequent (QDOX-182) so we had to change the implementation. If you use this in combination with innerClasses you should use Type.getFullyQualifiedName() to get the same result.

Upgrading to 1.10 or above

This section describes what needs to be done when upgrading to QDox 1.10.

Things that might break your code

The toString()-method in most of the JavaObjects under com.thoughtworks.qdox.models used to return the corresponding codeblock. This method has been renamed to getCodeBlock(). The toString() will follow the Java API Specs as described for each equivalent object under the java.lang-package. Some methods require extra attention, because there's not an exact match. Watch out for differences between Type and JavaClass.
Java APIQDOX
((java.lang.Method) aMethod).getReturnsType().toString()((com.thoughtworks.qdox.model.JavaMethod) aMethod).getReturns().toString()

com.thoughtworks.qdox.model.Type.getValue() will return the typeName for usage in the code. The new method com.thoughtworks.qdox.model.Type.getFullQualifiedName() will return the FQN as defined by the java specs. Normally they would return the same value, but pay attention when using inner classes.

Upgrading to 1.9 or above

This section describes what needs to be done when upgrading to QDox 1.9.

Things that might break your code

In both JavaClass and JavaSource the getPackage() returns an object of type JavaPackage instead of a String. To get the same result as before use getPackage().getName() .

Upgrading to 1.6 or above

This section describes what needs to be done when upgrading to QDox 1.6. For an extensive list of changes (most of them backwards compatible), please see the Changes Report.

Things that might break your code

In JavaClass the getInnerClasses() method has been renamed to getNestedClasses(). The old name remains as a (deprecated) synonym.

With support for generic types, we've introduced a bug affecting the use of "<" and ">" in initialisers (see QDOX-71).

Upgrading to 1.5

This section describes what needs to be done when upgrading to QDox 1.5. For an extensive list of changes (most of them backwards compatible), please see the Changes Report.

Things that might break your code

The DocletTag interface no longer contains a setContext() method. That information is now provided via DocletTagFactory, where createDocletTag() now requires an additional "context" parameter.

The parser now passes tag-data to Builders using a new TagDef structure.

Upgrading to 1.3

This section describes what needs to be done when upgrading to QDox 1.3. For an extensive list of changes (most of them backwards compatible), please see the Changes Report.

Things that might break your code

(Thanks to Peter Donald for contributing this list).

qdox-qdox-1.12.1/src/site/content/usage.html000066400000000000000000000061251204551233600207240ustar00rootroot00000000000000 QDox Usage

Entry Point

JavaDocBuilder is the entry point to QDox. It is responsible for parsing source code, resolving imports and storing the data.

To create it, all you need to do is call the default constructor.

JavaDocBuilder builder = new JavaDocBuilder();

Reading Source Files

Java source code can then be added to the JavaDocBuilder. Source can either be read one file at a time (using a java.io.Reader) or an entire source tree can be added recursively.

// Reading a single source file.
builder.addSource(new FileReader("MyFile.java"));

// Reading from another kind of input stream.
builder.addSource(new StringReader("package test; public class Hello {}"));

// Adding all .java files in a source tree (recursively).
builder.addSourceTree(new File("mysrcdir"));

Resolving Class Names

In order to resolve classes that have been imported using a wildcard (e.g. import java.util.*;), the ClassLibrary must be aware of other classes used in the project.

ClassLibrary has 4 ways to resolve classes:

  • By looking at other sources that have been added.
  • By searching through the supplied sourceFolders
  • By looking in the current classpath (including the standard JRE classes).
  • By looking at additional ClassLoaders specified at runtime.

All sources and sourcetrees added to the JavaDocBuilder will be parsed. This is often much more than required. To increase efficiency use the ClassLibrary to add sourcefolders. Consider these files as lazy parsed sources.

The current classpath is automaticly set by JavaDocBuilder. In most cases this shall be sufficient, however in some situations you may want resolve the full classes in external libraries.

To resolve classes from different ClassLoaders (e.g. 3rd party Jar files), the addClassLoader() method must be called on the ClassLibrary.

// Get the ClassLibrary
ClassLibrary lib = builder.getClassLibrary();

// Add a sourcefolder;
lib.addSourceFolder( new File( "src/main/java" ) );
lib.addSourceFolder( new File( "target/generated-sources/foobar" ) );

// Add a custom ClassLoader
lib.addClassLoader( myCustomClassLoader );

// Ant example : add the <classpath> element's contents
lib.addClassLoader( new AntClassLoader( getProject(), classpath ) );

It is important that additional ClassLoaders are added before any source files are parsed.

Navigating The Model

Now the files have been parsed, move on to navigating the model.

qdox-qdox-1.12.1/src/site/content/website.xml000066400000000000000000000016761204551233600211240ustar00rootroot00000000000000
Software index.html faq.html
Evaluating QDox download.html upgrade.html whouses.html
Project Information dependencies.html issue-tracking.html mail-lists.html license.html project-summary.html team-list.html source-repository.html
Project Reports changes-report.html changes.html apidocs/index.html
Using QDox usage.html model.html
qdox-qdox-1.12.1/src/site/content/whouses.html000066400000000000000000000175401204551233600213200ustar00rootroot00000000000000 Who is using QDox

Project Description How QDox is Used
AspectWerkz AspectWerkz is an Aspect Oriented Programming (AOP) toolkit for Java that modifies byte-code to weave in interceptors and mixins. Attributes can be used to associate interceptors and mixins with a specific class.
Avalon Phoenix Phoenix was a micro-kernel designed and implemented on top of the Avalon framework. It provided a number of facilities to manage the environment of Server Applications. Apache cancelled the Avalon project 2004 'MetaGenerate' is part of the Phoenix toolset and picks up @phoenix prefixed JavaDoc tags to make XML manifests for the components that will be laced together in more XML to make a complete server application.
Cocoon Apache Cocoon is an XML publishing framework that raises the usage of XML and XSLT technologies for server applications to a new level. Designed for performance and scalability around pipelined SAX processing, Cocoon offers a flexible environment based on a separation of concerns between content, logic, and style. The QDox Block reads in Java source files and fires out SAX events enabling processing by standard XML tools (such as XSLT).
Commons Attributes Jakarta Commons Attributes provides an API to runtime metadata attributes. Attributes are specified as doclet tags and then compiled into the classpath where they can be accessed at runtime (without requiring the source). The aim is to provide a framework similar to .NET attributes. QDox is used to extract the JavaDoc tags from the source files.
GWT-maven-plugin The gwt-maven-plugin provides support for GWT projects, including running the GWT developer tools (the compiler, shell and i18n generation) and performing support operations to help developers make GWT fit more closely in with their standard JEE web application development (debugging, managing the embedded server, running noserver, merging web.xml, generating I18N interfaces, generating Async GWT-RPC interfaces, and more) and environment (Eclipse IDE). QDox is used to generate the Async GWT-RPC interfaces based on their Service-classes.
Ivory Ivory provides easy integration between your exiting Java classes, Avalon services, and Axis. It allows easy deployment of soap services with none of the WSDD configuration that Axis normally mandates. Attributes are used to provide additional hints to Ivory about Java classes that cannot be determined via reflection.
maven-javadoc-plugin The Javadoc Plugin uses the Javadoc tool to generate javadocs for the specified project. When developers write code, they could forget to create (or update) the Javadoc comments. The and goals are interactive goals to fix the actual Javadoc comments.
Maven 2 Maven is a software project management and comprehension tool. QDox is used for extraction of Javadoc tags from source files to generate plugin descriptors
Mock Maker Mock Maker is a tool for automatically generating mock objects from custom classes to aid in testing the untestable. This supports the practises of Test Driven Development and eXtreme Programming. Mock Maker scans the source repository for any class/interface marked with the @mock JavaDoc tag and automatically creates the Mock Object for this that matches the class definition.
Nanning Nanning is an Aspect Oriented Programming (AOP) toolkit for Java that does not require a custom compiler. It uses dynamic proxies to weave in interceptors and mixins at runtime. QDox is used to allow aspects to be applied to classes by specifiying meta-data in doclet tags.
Paranamer Paranamer a mechamism for accessing the parameter names of methods of Java classes compiled into jars QDox is used to parse the source and generate the parameter names list.
Spring ME A version of Spring that not only has a very small runtime footprint (none), but also is capable of running on small handheld devices, since it does not rely on reflection.
vDoclet vDoclet is a framework for code-generation using Velocity templates, based on annotated Java source-code. vDoclet uses QDox to produce input-data for it's templates.
Voruta Voruta is a data access framework for embedding SQL statements in Java methods using custom JavaDoc tags and dynamic code generation at runtime. QDox is used to parse metadata and CGLib to generate implementation at runtime.
XDoclet2 XDoclet2 is a framework for code-generation using Velocity or Jelly templates, based on annotated Java source-code. It is a rewrite of XDoclet. XDoclet2 uses QDox to produce input-data for it's templates, as well as QDox' APITestCase to validate the generated sources.

qdox-qdox-1.12.1/src/site/resources/000077500000000000000000000000001204551233600172665ustar00rootroot00000000000000qdox-qdox-1.12.1/src/site/resources/blue2white.jpg000066400000000000000000000015021204551233600220400ustar00rootroot00000000000000JFIFC  !"$"$C" }!1AQa"q2#BR$3br %&'()*456789:CDEFGHIJSTUVWXYZcdefghijstuvwxyz w!1AQaq"2B #3Rbr $4%&'()*56789:CDEFGHIJSTUVWXYZcdefghijstuvwxyz ?QҊ+phHQNQP:ӅRcBQRƇSRe )íTQEKSTQNQH:QEIHQJ(pEK(L( (cC(E,c(P֖)2J(T:Ө) NQR1”QEK(pKE,hu(PJQI;6/2>k!1;?V1<)9%11>.>+=CEB)=/9HIG%@3?3C&=.D1A=DKLTDLo>LILf>JNOM7K,G=L1GQSPAMRR[2QVWU8O=NAQPVWYpZ\YNU5TPXKWGWGQ`b_UaX]_bpS]cclbdzfheKaI`G__f[fZd_hXalnkXhQdWfdllngpWjrtqurksxyvyxjvnwesdrhtiwrzw{pv}|twn{w~҃t~~v芌~э​퓔Еˑ⚜뜜♠գܦΣɢթÞ舘鲴櫱ல۶ٶεշǺ¿ܿȼſ,d H*\ȰÇ#JHŋ3jȱǏ CIɓ(S\ɲ˗0cʜI͛8sɳϟ@ JѣH*]ʴӧPJJիXjʵׯ`Ê%ٳ]PԀA rJ,0(q8>I5>fO;s1cjB\Ҍ1 1,#4Vi4,! g `x>Ts}1PYp^8r0Bδӎ<5dE6],48 0"K-jIeX84 <а6hVbAC&!I(ӴꪫB/t`+&F$(8E/J)Բ4|C9W8R25{&J2!BLִj 03qbv -D5?LGsS 3pu# 4d`k|<O>s XEg}*^ҽ zj5XCP9H@\c~d74ח}o>cC' -(=arl!vADȉ>q 1<@ы\@+$P<!M  >GDEjF5nUcd@ZA>r2 k\Dhp_|I"{l{ "g#Ax 0/cEJG(}x pbЌoxKx),E"VP2p86΁ot04q#57XVB{cl H1 'Ak%FD ր FHB! hÆN0F 3l;2ǯqTn(d#3@ ݸR*'k<఍W U<'F4 #."ݢ T=j΂K)42ɞrd;@Qj  2W3b@Mͮ,`/ž/.iZP>7L8!ҵ * 5\z` 4;}ܣy6(/y y*qdp[nd RbԲ"|#k QTMd4h(>q H2y8f4':Bn7lFGS"A׍J j>b}PJd>*"!r^a<"h5.ߨ/HK,qls<ۑgQ@)C'YHwaQ0F7ĹɎq .E({esD هn_ Kfr|Zv!~@f /,lU(aXJE?5! b|Ļ[q E"jJZу p/Q InG "!jqݾZoKFs$ [ \z-U)XrF, f9xe|~*~GD|ֈaƟ=*a0(E'j#kK% `3)^5+H[m}Z:rTɷڏ|v"6Fq9+!4ʰ1j W$[mRȠ # ;Kr9AӕW]?Ċݘu6| PTrςHPmS5B&!vhE7W eGψP@4Xqm@z>"-a9q^H^$"腅)P-pwdg @P 0~qS& Wfp rAW İ @5."4}WW >4`~pG~a9z: r '0cn#Fbh`fPsP @` 3/٧ 'x4:0Wٕ" | @$g<( r1{]eF`_p]cX2|0V[g nm׀pp\`x & -X's g!B k !*ܰ"0pFPӀﷇ8DB2` W:<{D8"DBP'/ WXЍD@ $H%A4pȆHS +XwX[NjH1 a2 / UJy 3wDQ|ߠ؍0]Ԑg(ЊDB.ath]!@q0Heaip9c $D@j+xj$W@s8qpyUtW )"!Њ+"Fyx1!:j@q}@lfa) # E~w"00X$ uUloh!yf_ rA*aw~u9@q*}w`{D Dd@5fH؍8 |%&A< %E8AFu@0"tA$`(`gat Mi驝y;gpi( hiPV [%7py0a9p&QGHuɠ;k FP NdADXI'c  O }P%*0J-@_%t*9`l8Z wdTdV/pi P.ʤ$xL까/ږqQPD ` ]X EJ@ٞ@s 1ؙfI`dS}[$zx AFY @qqP@ (‡XB&~P9}({@@p馢FAdk\*xI[ =WjI)p 0 ` p n@L 5d9d --@S*eԨ"0jl(~YƝ0z| IkjPvƪ jl7i8M(` t#a__c 1E0KJ)Zu=d~*`+ 1a`Uup37Ʊ1`v2t/j10Pİ +@L; ,/I&~`6<dו]l?ۀX[TNP{-HvI0Yl_+ѩ 10dS֞X 0 1c!@LNEr#j`e3ID[rQ0Ytc Jkq o2%Z5 C8BKAF$kDF̛I@pPs` `h w ׀]w@ X,_x(-8av4OPIySA$KHW )UNjDHBQ;D1usc0wLd`+lt4Ps &'E00f^ /g 0xlj` 9P[@hD By C 3@fjPsPevڦא@d#I[K +@ecFODp ` *bBtw\`ϻ:ˠ aGg IJP 0 5_θ0]kC[)k@ v`7?T0  "IP@T]X " AD\ Wyp` >;,(Wr PiS]@V]6ǘ )&hQ;Ɓot@fb @ WAګ mo^p |0ƀ}3-|P,ɢlT"s܀ DS"Q0Ѯa`6pLf5r1 J,AMWx.8 p91@ȰR%p  & صe2&' ? @ZSr!  O:Yxr w5G 0Ѐ ֞@p*6ڊp&0. ' S W,8r} ̠ aڀ @/@ j  wQ|@ W1 -WIڐǕt .cU@sȇpN.c 8d$mo  ak ې"} >25pSxG/]'b3dNIG  6` 6nc i0 ؠ  {. R @Y`WWsUgăj9~Y~a2Bnnm p .pJPP am gC_5 @ s`:H 1-a83/Q(w!.tʊ LJ!~} ЇՑA թ{kA@ P:^D bw"5A!B-2 O GQtXMI`G,1S3 ư\' `& l3263@/zY A.8 v  L ]qm +a `=+ hOT$QH B}*B)'o!W2!Sr!l;$B@V}?)*ml$@ C^X'C#@ ?]/i^'Q{Sg\8\ta;ye(^xuF0x8p f]Q|G^Ś)=`#M1[(Zm.R&ynjDv 8Q`…h#NYWɾ~N{SƏzML"I~Qb]o*z=J[V)J\V8#KQrͮytÞ];v|};+t|##Fy1V~[W<_J{~ jhrۭ79n8!' Ǿ0ÌC9'DbNDC0CVE 3qD?| (iTP#%dnY`1JCJ(2K!餄T닩lƕN90Aa`M4IG4N;ӽ>32e9.nM6ElȡRK/E1{O:y t38-EoTl1x SYg5 1о@B!6g2$` X5Zioh**B򌡩Ŵ+~uNrB7P?Gny"@3! P`0%t8j2մdZ:t? _ ;y rc^ TjUW.":A" M7t'@n(o$QUƴNWՔ$T8~{\p]]+7T-D'WL'EhHRW*[P~Wۃ/^XC\nHzI?aw ߘc&NV@6Q+grZ+eBe/oxg j'k|pѢBJÑm+hVl2ֵwjGX'7fP|AE3 HUW(&9ҖOk!ҕAP cjGˀ^5|S0DTDzi~4j)MY5q ?Nޗ,+fl P5Bȷm1W,/-ɐ 2`6h9mt?ņ`H 5[X W7X#M!AKih2\Gx K88w Bj 9S{'4yXǰSv;=fYqt& d28T6_)B=jdߨ bPrSHNkE}@p|Ald/őUȲ?~ͅܛ!ͺ^Zhb^@N-3qtZ1МќVآᷝ.þ+Z!{,G ;fnHWR ͷ}sų.`jcy۶4-NgwL>XrJQ@Hmk5G}O"_hhH*P*k è *1H硪$r%^spD"Py~I8sOrh9\c$U6dVk}Nu+ukmKw$=AF+&nˌT4W5,J8L.)KpOֳ5{醨|ph\pl:"}{I<fU$PJP`R)T*3xėT*1dGFdp?#xy.g<鶸]p 8w }a*TY֚GpKiPJlTgE 0fb,E!kZ_4kKbѴ,a3"0dL3t.. !lj+ W7f#4?TǾyXG++AF.~2Ej#;1pM`hp?$ZᶔL#?ŏ=h2cY1q&i`Y 0}7㋮OcZ {^:I{#mvOd@xPOݕO'ud'6l u:XKaf)N22L uq?2o܏7@Yiyruw *IQj)M7bHmLmPye0ܛZaGJ35Z ̻?z1{ 4G[›e'/hP䣁>.6oZ\C`;{ݒ~}yֵ-؉Ao`Ed*̀;8pd=l8X%'9MoV1iZԐdpasYvQޏ"7Mbzf W@mqSPm4 G?qY(s0@g.@pbьo[oa`yDS}[eb/.o!E j}~o(Ny#&`K|<2E6D-3 $䐎"Ìp0v71'^^g"H3r;|t|ko&5ぃ]Xc5 1'NrMjyfhb!"DΜā ft֗(?Q"7䗔?\ȶP*_<)Ͻƽm2VqưY0T E[p6\V2,q3gQmx\܀|VŲÙNF97f%1,3oR|jh(>Ѣ"g42v9aLSQ3v?kW~у=TyH]s}^|}~`JLb$Wau1 xޖkb4{re+Bۏ=\ӟ#tԳ- MynUE,X?66 /wʔ*3;ppwn%j*? 8E:SL5EZX[KVZZpt?Y j] ߾0VJm0l9생[ hN4s/W뾇?EA /ԇrym74<|sy13:sǛF>崩kaܕ,礮'*-֗N`m yo/؋podښ8lhj> n^ߵ/᣹ prV@pJ4 dYriYngE?;jL>z[NX n uI`WVOy0sr{Oa,$aPV҇;Oi)qTBSEAJO=,F8BL]2|.kGϏZNM>Ն%ֻDDyɽku6V,`wbb".+x8&Qy B$čնv1]LG;<0n{{8Cq=V\q؇&0{^:p Ri'I|;.#xoM% "ؘ!9'CY5=~OXKiu8I<њ~> SP5Hֺ!W/OjTU^X&, fxvX, |wѺ~4jr44fMe hЩ.Oj:'F4C!c#@d#h_Iݨ|U3[pw5 xWy^#<4AܪGqaXR:YсVM"oqŹO]6])IuڋÜܑ\JB+ TKK\PAv?}dUo,YNd\pawax* b(0H(L r}=K*|Zp&:`eH1]= 78Cm^1c0mX˛TGn2.gYxl}}t/OHs!ima n KؐxVUϔt&5u,, "4u-x+KzS"I)!գf:Kh$x}|肽ȼ0*p~ wt%x r9k?cMrֲ{H=E۸'肮{M9%ZKdm۶Z4< vk蟾/=rT`k*1]ґGgt.KgZ [J*@9yjn..N gn3CZ2Mނ6h<J i& !}aoh@?hf~iɪ{DŽor yR}^V~$n{bm%bb46[B{].ϴ6օ{MiC2R f>BY|SQ(I\7, _7pY0wnF#4Ҧ/g`nkG:voOQGvZki Uoa4"/s! "~|gS'ډ24q{tu(P!ILV'@,|p@ɘ\k퍟3- e$N郯88h c':N]\+fHIː'}#7± LvjP>s{2l<(|̔gXY/pv ] s';*z%O ylvWՃŋKG]~WI<,O(u,[/F_T 5t̺d=8ӠvAܹ$dPC" ^B S^K>L[x=A#ۖ2]Ib(z>|Oo+ | KX;9($bD/D'-@~ u?y0h8{ieƁ|T I}ɦn7ԡX=ǿBŵu+V4MXPLgM 2 % !|fweGdp2G!g94 >p$j5Sz/[qqn?) WElSXod>\]e˖6pY,{H.baSæ<_8D ֤Nvp[|.&0 GS*><$rpE&N!YILegfxp~*BgUj,;[4:o#tEe=c^ =;bȡT| HE%$*I4:/lNt`7w,Ir% bV)`[MF+$*dzĬ ]\VPChkM8}K,?O|a厁n%Zà9$!_t?7o1Y+6b?SkHW<@s`*bONtD]b *Yl^a+Yݧ:18%&@@UW^T7?RfkBs Jk0%SLUHި\3@$wwlzͶ}BVh }w^S>aT0 ,CdLw0E~cYR߇X{#ʵI J h(Yf0>lDMnk:t҇8lK@!2tX|s\E:?^P$/d34DGOwLWڎt63< *O'ϳ߂8 }Z/nqQ&38Ll+ƇDyUՃ8XFvԘVКX̟;fgQTj5C?~lke, ` 6. K K )xyf!I^KQG5hc/n=Nt_A_ˆtGϫԭK󯭄懻qee(7JOenT>WEq{b  By1UFi>CaSL UZx6WTx锅(}G@| %#'&ߣ?+g5ThwX$ȚWрO0n,mX(Օ^gWu6LK,wYEt\ɋn0B Ud(ۖ{2:5,N 3h.0iliq4.P*ƀ3LTiq-rUe;u"@;n%R ,S_POX{ͫW}=?{Gmwf/VF͒{ˌ,^&Ȱ7*mw[K-Rh4@W w}$/,&"$1-RW@(( pS뱕KYOj=apؕѡeEuԱli9yZ>f0qQH/c|?(A|HГ[%|2q LGU\z؛ jp:>9D+--mR.vx߮w0v rW;gW 5on.l\73`pNYxhMUk6Z7wV?+_4ou] 'pE{bŬ^jU>4_Ƣ]Axťohj*0`,LX 53d]xB@IBMHvrӠ K3գS1@|q//x<BYƐt|cR F(MMM i NPӹ%+% T-<219Dx*Q$2l~"P-w}o˖àJ) 28a fB&g5LH'u^ :L3H'gEoh_=]jos8lvl^O|r?^mۘN~桯~vs<,cQ1ۆĴK@XH' b^W>.K4'*.Bm=eP%yI|A{D7> 9 g gm)㮒ke-ɌHyCCᑔ<dGeL#Gct0$A"'d}ή-:Ul 9׻r/itͫwͮr}W!ru^_ˋ WZa!fu2(ٹ~ԂP%P5l7Rm-'b>zG?2%:XSZX*ֻ!I5YJ=i6XoC%ZM(7ޙyQ\bSڪ9ZQa!(y'h BgNJI2`~BA'(Apc"+!fvXլe⥴֙>M{m]rӟ%v,w$ @PP.GDsǁ#7' Q'( 5jl4zdJ6 NE?b$=_UzZgGY9>ܜ\+"HTZMdC,d~?۞.-aAkyfϲ&:.Qqx? ukz)̾l2,.ZMuXtW/`題Z=VcYBZuQSU^jdrfu=t\l{sVWLآ2g;\.׹8fFXwwzrFU0*/%0Ӊ*#~㿨 TRP!X'M*hNhO3' h+~3+V8DU']I?X ?ڝ;W"ieX]w 0M3|mwC1~K 鱸5Q:5ݤ]"S{`\-w\Bv^3H"a([(d{)[ΌecNϱrSF(bƌX1_Myӟ32UNB 9Xa,/gzATEB^=EGA\א,C>D/@$={ti^˞h*lwj^"Nq !>J8Es񍕞 1$PȖyC+oW<1~ #Y QH3Y;v\ _H( rKuWV777èvvvb%h-_I~ HƧGDŽZJ֊*uZi*I*4T(_L$“fI5VsGjb.$՚k`:G suz3eb`\R $f\\lzZXP\V)꾸ZzƯ|; fq.ڢ|WQz"%@jcJDfPOq :NJg$K "9 w*l>=J=r6mղBa-:>.s-E@fݬ=hpȖaANd,2ebT{/3]{s=>D.)pɺH-jI^~{ !՜}e@k䗌=OnCBCRMK9 fEf)p ?~?jDJ6THnE?)d#XQtaMM+C2.@/(AL(h1XQsS6W&TRߔ C]*;(wҠd$̒AL}P 18Hh@e–8 7-H J7,< @h_5kYs'r^D1-mMrhG%D&_VMe a] zw]rBYڻ VX$a`il APAV˅K 7_w$J88+kK`8" X0s U'=TQ5xF%QLfSXꠐJBjEv;.0wJيʰٔxWGlۼ4ن()#ԤC\8zlHymMMP\<*i,b%ts}`oKeEUarqlZpD%G"knnf^>3Ѱwx+m+*L$KE @8.p#=ZHv)tBĻO~k[TJ 7FNdGUþA'suG#C0;ư JA>I%R.G]-c^? 38 s@]J UyXG[/9S"@hw2~p\]Q_,-x Ɵ[U)8:;|X[}xJ6K `_.]2pM}c+/v\R(e+ZÆ߫lՓ$L$U'Bz28n=`Zp\,eCc+oLJs,a2ݹ n,vddAa仜"]V>sEȡT'p=zpLzp:@"k{\Z:ZCNœvYtzvjgCUJ a*ifyĖJMk{FEla/V_,侁+o%PWw޺_2#wS ON >iϝw_Tó)!t;iXv):/9&#?aw!i%=RvVY&y"a\tPYrɮ{ͷRjHv/]:{nO9鲠 +"n" EJT@Ҫ޳ͨ "֮p Ti 9NV̯R_jtMfL|UQF6OKT^;*Ih);i Jeecc_9pij;썟ޮI5lQa}Rߪ.aSC9 o")Z2xEx㍭cs:Zs~MW*- VɍäF a=+8mYLM 3*bEؓyyUua 4i ^te:Hĺnq@VH5*O_|#TivC;8\5MbaKqvJg׋ݸwpw+{I#*CU ϽgvY,QOCrK ҉7x ?X a4- PNk01 H\t+۝ZUOcӘMWW HK? =<>Q쁽TTZW5߱Եˇ}4krwi/5q8]!/)o:XX|roΚ XLT&.WD3K篾dom]_#\f'Fa]1@[뇽cX!,%HUOd=K(C/t3vg' p)'GrG/\X[Msm]N93?zuĢ[KKW7 o=Ol;'"?`wÛ}dGX+*闖'S6k<|Ec5#$[=-z,d̛ E~1EGw?7bƇx\FK:;$q5 n8|#vFW0ʅ(`^}Z E`QPǦ'gw:0L|;Ʌξt?Tw-0u슶7{Cu'h:jbmjj8PpGuR9c ů=u ?Kq XQ x|W'{H2 Fh7}$'li"J޲&F" RWV{}̗F*95., BDL|26 L4Nm4),km.g 57б@MலXF#V64/t׾ԒEɧǏ웞`6bj9Hs|?|«2b\ Xfۤ*-,Mں/w;)TO_2sƶϬ=:Fqv~ohPO>TP:5 zcXR(w4ˋ=Ҵ UF \PBfg-4 W{}֥UX0Uf]#[F^ETp=űxӎe <\n5}#k\R ]s`*ڠ9J ,%ݜ;n7-X/GǷPd$N3I@z jCOY{y"ʘLh%Xx[g6(}SeK7h@ <zt0KS「T $M #׹@ A| Ƌkk:v+9 䦼[$DzrW>B]>/9{n?{Oz{Krb8c7uSv4Sg ]+f(QxULۜs7D7DCPxݮWv<<ЩJFZgF W6 s9G> +v>'=v*Z #OSo`!`8XC~ۿq yCfSx.p1n_6c@7=xHaPmżDCژ]z>m6gP'(46Nbmÿ>Uٱ0tK) _n%oFf._]k1$cӵgf~->z'dGFI%VEUR\7!dUQ2,SW<%xm3ϛ ]ljNR i .+Y!ZbƖή|pG+Au ]ծcX 2\*qp)W;QX1'M/<`#ҿB wE ˛{qa8H,@o|>ݪ$*}3.Ƴ==mK/AaJ"<O'%_"늸U y1$52^^1ѷ1kݘ` nV$'MKR+$njrǶy/HH`KNH[3_3t@T8 &QSm%Kig)-iTV+N[ ǷvP7|o뻛l:**D߭)G x\6+ϠM̟PگwTz.*vG(͸d+{$p=05N#'}?t6f"mZ ԣM%%cNE^ 6JtxK8]k /l[<';`Iuij۟".١@mS{ns3_ӵ; U nRyJ3(}쉬4caH+tZ>NTo;;[ UAg  UA7? y1Tm\F-gFg>gT׃%TW"*o%DlZ>Zt)3ߋVH @O]#g2TnQV*W zF/N[|I=\,"7/8_'ᖶyms_:ضb_:]`Ba>+]E"$襇W&Sҗe(VAT23'2WYYɳF𻌅m̯s.zU)!w#=-V_tvb*]]0ܠnH둸5/OU`aisj\,&e&qZQ̪gFEZܸgA(7"D\G~4/f=Adt}n߿;7UԶs:zȤSSڠ{׆l:E}d̆ b]Y@tV".XOdQLs2yf8/ɾ}3vR6aW.X.w?TN͊.+)KfejJKJϗHJ9L:29<`zDvA+0* ~[:P_}8q5J{=p2T\p8a|ց+ȗ@GAG2]dଂ;6W:r.( [9Y/psUhs댢EEk( Ct J?t~qhQBP@s 9y n1ج8Vd/v_@u4UO HFtb U2>C)aljVJ٩ jll:Ŵ=ΣM6MZۈVipIkJcj'k0Gr%-y|+Ѹd7*aE3N{@0X*\.gRU X[HyJ(E`Y͈_ wod,:TYA^hͪ*^*~[K* b̔tT5%SnU 7tDrYTTء:ćE|ˮR_+U1V cvɲ UʖjdUSPzt O;W/)]*e'̒/W~F]GMR fNy%~Ϧi31=_L$*g{TEؙ}1#4~7 ᬞTi@IMU[P zܑ +M}feUcSƉ͇ vђge671%ߣSIOu#2庑)s6HBN@Bwo~z::I(}`нJǻ\rOgT%v2i d*כ{FA.zi;Hz Af60 - {xStH\bљ2=䟇TԾ8umW?| q f VWm@I,;iۧ羆cP2^~K?Ѵ@1xS_1 %x/xVXq:Ă?8Ax{?\u[IENDB`qdox-qdox-1.12.1/src/site/resources/white2blue.jpg000066400000000000000000000013701204551233600220430ustar00rootroot00000000000000JFIFC  !"$"$C" }!1AQa"q2#BR$3br %&'()*456789:CDEFGHIJSTUVWXYZcdefghijstuvwxyz w!1AQaq"2B #3Rbr $4%&'()*56789:CDEFGHIJSTUVWXYZcdefghijstuvwxyz ?j-V3R^Nj(H-TWL $TTWDi%U%E %w"ꤴQ]00R^RZ(*KުKҊ+&*KU&"j袺ba"袺"sȩ7z(?qdox-qdox-1.12.1/src/site/templates/000077500000000000000000000000001204551233600172525ustar00rootroot00000000000000qdox-qdox-1.12.1/src/site/templates/site-template.vm000066400000000000000000000010271204551233600223730ustar00rootroot00000000000000 #if($title.startsWith('QDox - ')) $title.substring(6) #else $title #end $bodyContent qdox-qdox-1.12.1/src/site/templates/skin.html000066400000000000000000000034301204551233600211040ustar00rootroot00000000000000 QDox - ${title} ${head}

${title}

${body}
<#list sitemap.sections as section>
qdox-qdox-1.12.1/src/test-resources/000077500000000000000000000000001204551233600172775ustar00rootroot00000000000000qdox-qdox-1.12.1/src/test-resources/qdox-140/000077500000000000000000000000001204551233600205545ustar00rootroot00000000000000qdox-qdox-1.12.1/src/test-resources/qdox-140/X.jav000066400000000000000000000001101204551233600214550ustar00rootroot00000000000000interface X { void paramWithNonAsciis\u00E4\u00F6\u00FC\u00DF(); }qdox-qdox-1.12.1/src/test-resources/readme.txt000066400000000000000000000000761204551233600213000ustar00rootroot00000000000000this folder is introduces to have a solid way to test qdox-148qdox-qdox-1.12.1/src/test/000077500000000000000000000000001204551233600152675ustar00rootroot00000000000000qdox-qdox-1.12.1/src/test/com/000077500000000000000000000000001204551233600160455ustar00rootroot00000000000000qdox-qdox-1.12.1/src/test/com/thoughtworks/000077500000000000000000000000001204551233600206155ustar00rootroot00000000000000qdox-qdox-1.12.1/src/test/com/thoughtworks/qdox/000077500000000000000000000000001204551233600215705ustar00rootroot00000000000000qdox-qdox-1.12.1/src/test/com/thoughtworks/qdox/AnnotationsModelTest.java000066400000000000000000000364661204551233600265700ustar00rootroot00000000000000package com.thoughtworks.qdox; import java.io.StringReader; import java.util.ListIterator; import junit.framework.TestCase; import com.thoughtworks.qdox.model.Annotation; import com.thoughtworks.qdox.model.JavaClass; import com.thoughtworks.qdox.model.JavaField; import com.thoughtworks.qdox.model.JavaMethod; import com.thoughtworks.qdox.model.JavaPackage; import com.thoughtworks.qdox.model.annotation.AnnotationAdd; import com.thoughtworks.qdox.model.annotation.AnnotationConstant; import com.thoughtworks.qdox.model.annotation.AnnotationFieldRef; import com.thoughtworks.qdox.model.annotation.AnnotationTypeRef; import com.thoughtworks.qdox.model.annotation.AnnotationValue; import com.thoughtworks.qdox.model.annotation.AnnotationValueList; import com.thoughtworks.qdox.model.annotation.EvaluatingVisitor; public class AnnotationsModelTest extends TestCase { private JavaDocBuilder builder; private EvaluatingVisitor evaluatingVisitor = new EvaluatingVisitor() { protected Object getFieldReferenceValue( JavaField javaField ) { throw new UnsupportedOperationException(); } }; protected void setUp() throws Exception { super.setUp(); builder = new JavaDocBuilder(); builder.setDebugLexer( true ); builder.setDebugParser( true ); } protected Annotation checkClassAnnotation( String source ) { builder.addSource( new StringReader( source ) ); JavaClass clazz = builder.getClassByName( "Foo" ); assertEquals( "Annotations", 1, clazz.getAnnotations().length ); Annotation annotation = clazz.getAnnotations()[0]; assertEquals( "Annotation name", "Annotation", annotation.getType().getJavaClass().getFullyQualifiedName() ); return annotation; } public void testMarkerAnnotation() { checkClassAnnotation( "@Annotation\nclass Foo {}" ); } public void testEmptyAnnotation() { checkClassAnnotation( "@Annotation()\nclass Foo {}" ); } public void testAnnotationAnnotation() { checkClassAnnotation( "@Annotation(@NestedAnnotation)\nclass Foo {}" ); } public void testConstAnnotation() { checkClassAnnotation( "@Annotation(1)\nclass Foo {}" ); } public void testAnnotationConstants() { String source = "@Annotation( f = 1.0, d = 1.0d, i = 1, ix = 0x1, l = 1L, lx = 0x1L, c = 'c', s = \"string\" )\nclass Foo {}"; builder.addSource( new StringReader( source ) ); JavaClass clazz = builder.getClassByName( "Foo" ); assertEquals( "Annotations", 1, clazz.getAnnotations().length ); Annotation annotation = clazz.getAnnotations()[0]; assertEquals( "Annotation name", "Annotation", annotation.getType().getJavaClass().getFullyQualifiedName() ); assertEquals( "Properties", 8, annotation.getNamedParameterMap().size() ); AnnotationConstant f = (AnnotationConstant) annotation.getProperty( "f" ); assertEquals( "f", new Float( 1 ), f.getValue() ); AnnotationConstant d = (AnnotationConstant) annotation.getProperty( "d" ); assertEquals( "d", new Double( 1 ), d.getValue() ); AnnotationConstant i = (AnnotationConstant) annotation.getProperty( "i" ); assertEquals( "i", new Integer( 1 ), i.getValue() ); AnnotationConstant ix = (AnnotationConstant) annotation.getProperty( "ix" ); assertEquals( "ix", new Integer( 1 ), ix.getValue() ); AnnotationConstant l = (AnnotationConstant) annotation.getProperty( "l" ); assertEquals( "l", new Long( 1 ), l.getValue() ); AnnotationConstant lx = (AnnotationConstant) annotation.getProperty( "lx" ); assertEquals( "lx", new Long( 1 ), lx.getValue() ); AnnotationConstant c = (AnnotationConstant) annotation.getProperty( "c" ); assertEquals( "c", new Character( 'c' ), c.getValue() ); AnnotationConstant s = (AnnotationConstant) annotation.getProperty( "s" ); assertEquals( "s", "string", s.getValue() ); } public void testAnnotationConstantsControlChars() { String source = "@Annotation( s1 = \"a\\nb\", s2 = \"a\\nb\", s3 = \"a\\rb\", s4 = \"a\\tb\", s5 = \"a\\u0009b\" ) class Foo {}"; builder.addSource( new StringReader( source ) ); JavaClass clazz = builder.getClassByName( "Foo" ); assertEquals( "Annotations", 1, clazz.getAnnotations().length ); Annotation annotation = clazz.getAnnotations()[0]; assertEquals( "Annotation name", "Annotation", annotation.getType().getJavaClass().getFullyQualifiedName() ); assertEquals( "Properties", 5, annotation.getPropertyMap().size() ); AnnotationConstant s1 = (AnnotationConstant) annotation.getProperty( "s1" ); assertEquals( "s1", "a\nb", s1.getValue() ); AnnotationConstant s2 = (AnnotationConstant) annotation.getProperty( "s2" ); assertEquals( "s2", "a\nb", s2.getValue() ); AnnotationConstant s3 = (AnnotationConstant) annotation.getProperty( "s3" ); assertEquals( "s3", "a\rb", s3.getValue() ); AnnotationConstant s4 = (AnnotationConstant) annotation.getProperty( "s4" ); assertEquals( "s4", "a\tb", s4.getValue() ); AnnotationConstant s5 = (AnnotationConstant) annotation.getProperty( "s5" ); assertEquals( "s5", "a\u0009b", s5.getValue() ); } public void testNestedAnnotation() { String source = "@Annotation( { @Inner(1), @Inner(2) } ) class Foo {}"; builder.addSource( new StringReader( source ) ); JavaClass clazz = builder.getClassByName( "Foo" ); assertEquals( "Annotations", 1, clazz.getAnnotations().length ); Annotation annotation = clazz.getAnnotations()[0]; assertEquals( "Annotation name", "Annotation", annotation.getType().getJavaClass().getFullyQualifiedName() ); assertEquals( "Properties", 1, annotation.getPropertyMap().size() ); AnnotationValueList list = (AnnotationValueList) annotation.getProperty( "value" ); assertEquals( "Inner Annotations", 2, list.getValueList().size() ); for( ListIterator i = list.getValueList().listIterator(); i.hasNext(); ) { Annotation inner = (Annotation) i.next(); assertEquals( "Inner " + i.previousIndex(), "Inner", inner.getType().getValue() ); } } public void testExpressionAnnotation1() { String source = "@Annotation( 1 + 1 ) class Foo {}"; builder.addSource( new StringReader( source ) ); JavaClass clazz = builder.getClassByName( "Foo" ); assertEquals( "Annotations", 1, clazz.getAnnotations().length ); Annotation annotation = clazz.getAnnotations()[0]; assertEquals( "Annotation name", "Annotation", annotation.getType().getJavaClass().getFullyQualifiedName() ); assertEquals( "Properties", 1, annotation.getPropertyMap().size() ); AnnotationAdd add = (AnnotationAdd) annotation.getProperty( "value" ); assertEquals( "Left", new Integer( 1 ), ((AnnotationConstant) add.getLeft()).getValue() ); assertEquals( "Right", new Integer( 1 ), ((AnnotationConstant) add.getRight()).getValue() ); } public void testExpressionAnnotation2() { String source = "@Annotation( \"value = \" + 1 ) class Foo {}"; builder.addSource( new StringReader( source ) ); JavaClass clazz = builder.getClassByName( "Foo" ); assertEquals( "Annotations", 1, clazz.getAnnotations().length ); Annotation annotation = clazz.getAnnotations()[0]; assertEquals( "Annotation name", "Annotation", annotation.getType().getJavaClass().getFullyQualifiedName() ); assertEquals( "Properties", 1, annotation.getPropertyMap().size() ); AnnotationAdd add = (AnnotationAdd) annotation.getProperty( "value" ); assertEquals( "Left", "value = ", ((AnnotationConstant) add.getLeft()).getValue() ); assertEquals( "Right", new Integer( 1 ), ((AnnotationConstant) add.getRight()).getValue() ); } public void testFieldRefAnnotation() { String source = "@Annotation( java.lang.Math.E ) class Foo {}"; builder.addSource( new StringReader( source ) ); JavaClass clazz = builder.getClassByName( "Foo" ); assertEquals( "Annotations", 1, clazz.getAnnotations().length ); Annotation annotation = clazz.getAnnotations()[0]; assertEquals( "Annotation name", "Annotation", annotation.getType().getJavaClass().getFullyQualifiedName() ); assertEquals( "Properties", 1, annotation.getPropertyMap().size() ); AnnotationFieldRef value = (AnnotationFieldRef) annotation.getProperty( "value" ); assertEquals( "type", "double", value.getField().getType().getValue() ); assertEquals( "class part", "java.lang.Math", value.getClassPart() ); assertEquals( "field part", "E", value.getFieldPart() ); } public void testPrimitiveClassAnnotation() { String source = "@Annotation( int.class ) class Foo {}"; builder.addSource( new StringReader( source ) ); JavaClass clazz = builder.getClassByName( "Foo" ); assertEquals( "Annotations", 1, clazz.getAnnotations().length ); Annotation annotation = clazz.getAnnotations()[0]; assertEquals( "Annotation name", "Annotation", annotation.getType().getJavaClass().getFullyQualifiedName() ); assertEquals( "Properties", 1, annotation.getPropertyMap().size() ); Object value = annotation.getProperty( "value" ); AnnotationTypeRef ref = (AnnotationTypeRef) value; assertEquals( "value", "int", ref.getType().getValue() ); } public void testClassAnnotation() { String source = "@Annotation( java.util.Set.class ) class Foo {}"; builder.addSource( new StringReader( source ) ); JavaClass clazz = builder.getClassByName( "Foo" ); assertEquals( "Annotations", 1, clazz.getAnnotations().length ); Annotation annotation = clazz.getAnnotations()[0]; assertEquals( "Annotation name", "Annotation", annotation.getType().getJavaClass().getFullyQualifiedName() ); assertEquals( "Properties", 1, annotation.getPropertyMap().size() ); Object value = annotation.getProperty( "value" ); AnnotationTypeRef ref = (AnnotationTypeRef) value; assertEquals( "value", "java.util.Set", ref.getType().getValue() ); } protected void assertAnnotationValue( Object expected ) { JavaClass clazz = builder.getClassByName( "Foo" ); assertEquals( "Annotations", 1, clazz.getAnnotations().length ); Annotation annotation = clazz.getAnnotations()[0]; assertEquals( "Annotation name", "Annotation", annotation.getType().getJavaClass().getFullyQualifiedName() ); assertEquals( "Properties", 1, annotation.getPropertyMap().size() ); AnnotationValue value = annotation.getProperty( "value" ); Object v = value.accept( evaluatingVisitor ); assertEquals( "Value", expected, v ); } protected void assertAnnotationExpression( String expression, Object expected ) { String source = "@Annotation(\n" + expression + "\n) class Foo {}"; builder.addSource( new StringReader( source ) ); assertAnnotationValue( expected ); } public void testPrecedence() { assertAnnotationExpression( "2 + 2 * 5", new Integer( 12 ) ); assertAnnotationExpression( "2 * 5 + 2", new Integer( 12 ) ); } public void testLogicalExpression() { assertAnnotationExpression( "true && false", Boolean.FALSE ); assertAnnotationExpression( "true || false", Boolean.TRUE ); assertAnnotationExpression( "!true", Boolean.FALSE ); } public void testBitExpression() { assertAnnotationExpression( "1 & 3", new Integer( 1 & 3 ) ); assertAnnotationExpression( "1 | 3", new Integer( 1 | 3 ) ); assertAnnotationExpression( "1 ^ 3", new Integer( 1 ^ 3 ) ); assertAnnotationExpression( "~1", new Integer( ~1 ) ); } public void testSignExpression() { assertAnnotationExpression( "+1", new Integer( 1 ) ); assertAnnotationExpression( "-1", new Integer( -1 ) ); assertAnnotationExpression( "--1", new Integer( 1 ) ); } public void testAddSubMultDivExpression() { assertAnnotationExpression( "8 / 3", new Integer( 8 / 3 ) ); assertAnnotationExpression( "8 * 3", new Integer( 8 * 3 ) ); assertAnnotationExpression( "8 + 3", new Integer( 8 + 3 ) ); assertAnnotationExpression( "8 - 3", new Integer( 8 - 3 ) ); assertAnnotationExpression( "8 % 3", new Integer( 8 % 3 ) ); assertAnnotationExpression( "\"a\" + \"b\"", "a" + "b" ); } public void testShiftExpression() { assertAnnotationExpression( "8 << 2", new Integer( 8 << 2 ) ); assertAnnotationExpression( "8 >> 2", new Integer( 8 >> 2 ) ); assertAnnotationExpression( "-1 >> 2", new Integer( -1 >> 2 ) ); assertAnnotationExpression( "-1 >>> 2", new Integer( -1 >>> 2 ) ); } public void testLiteral() { assertAnnotationExpression( "1", new Integer( 1 ) ); assertAnnotationExpression( "1l", new Long( 1 ) ); assertAnnotationExpression( "1.0", new Float( 1 ) ); assertAnnotationExpression( "1.0d", new Double( 1 ) ); } public void testParenExpression() { assertAnnotationExpression( "2 + (2 * 5)", new Integer( 12 ) ); assertAnnotationExpression( "(2 + 2) * 5", new Integer( 20 ) ); } public void testCompareExpression() { assertAnnotationExpression( "1 < 2", Boolean.TRUE ); assertAnnotationExpression( "1 > 2", Boolean.FALSE ); assertAnnotationExpression( "1 <= 2", Boolean.TRUE ); assertAnnotationExpression( "1 >= 2", Boolean.FALSE ); assertAnnotationExpression( "1 == 2", Boolean.FALSE ); assertAnnotationExpression( "1 != 2", Boolean.TRUE ); } public void testQueryExpression() { assertAnnotationExpression( "1 < 2 ? 0 : 3", new Integer( 0 ) ); assertAnnotationExpression( "1 > 2 ? 0 : 3", new Integer( 3 ) ); } public void testCastExpression() { assertAnnotationExpression( "(short)1", new Short( (short) 1 ) ); assertAnnotationExpression( "(long)(short)1", new Long( 1 ) ); assertAnnotationExpression( "(int)((short)1 + (long)3)", new Integer( 4 ) ); } //from Qdox-98 public void testPackageWithAnnotation() throws Exception { String source = "@javax.xml.bind.annotation.XmlSchema(namespace = \"http://docs.oasis-open.org/wsn/br-2\")\n" + "package org.oasis_open.docs.wsn.br_2;\n" + "public class Foo {}"; builder.addSource(new StringReader(source)); JavaPackage jPackage = builder.getClasses()[0].getPackage(); assertEquals("org.oasis_open.docs.wsn.br_2", jPackage.getName()); assertEquals("javax.xml.bind.annotation.XmlSchema", jPackage.getAnnotations()[0].getType().getValue()); assertEquals(2, jPackage.getLineNumber()); } // http://jira.codehaus.org/browse/QDOX-135 public void testAnnotationInMethodParamList() { String source = "" + "class Foo {\n" // + " @X()\n" - does not affect test. + " public String xyz(@Y(1) int blah) {\n" + " }\n" + "}\n"; builder.addSource(new StringReader(source)); JavaClass clazz = builder.getClassByName("Foo"); JavaMethod mth = clazz.getMethods()[0]; assertEquals("Foo", clazz.getName()); } } qdox-qdox-1.12.1/src/test/com/thoughtworks/qdox/AnnotationsTest.java000066400000000000000000000236241204551233600255770ustar00rootroot00000000000000package com.thoughtworks.qdox; import java.io.StringReader; import junit.framework.TestCase; import com.thoughtworks.qdox.model.Annotation; import com.thoughtworks.qdox.model.JavaClass; import com.thoughtworks.qdox.model.JavaMethod; import com.thoughtworks.qdox.model.Type; import com.thoughtworks.qdox.model.annotation.AnnotationFieldRef; public class AnnotationsTest extends TestCase { private JavaDocBuilder builder; public AnnotationsTest() { builder = new JavaDocBuilder(); //builder.setDebugLexer( true ); //builder.setDebugParser( true ); } public void testShouldIgnoreSimpleClassAnnotation() { String source = "" + "@Fnord\n" + "public interface Foo extends Bar {}\n"; builder.addSource(new StringReader(source)); assertEquals("Foo", builder.getClassByName("Foo").getName()); } public void testShouldIgnoreSimpleMethodAnnotation() { String source = "" + "public class X {\n" + " @Fnord public void snort() {}\n" + "}\n"; builder.addSource(new StringReader(source)); JavaClass fooClass = builder.getClassByName("X"); assertEquals("X", fooClass.getName()); assertEquals(1, fooClass.getMethods().length); assertEquals("snort", fooClass.getMethods()[0].getName()); } public void testShouldIgnoreMethodParameterAnnotation() { String source = "" + "public class X {\n" + " String field = new String( \"hey\" );\n" + " public void setX(@name String x) {}\n" + "}\n"; builder.addSource(new StringReader(source)); JavaClass fooClass = builder.getClassByName("X"); assertEquals("X", fooClass.getName()); assertEquals(1, fooClass.getMethods().length); assertEquals("setX", fooClass.getMethods()[0].getName()); } public void testShouldIgnoreComplexClassAnnotations() { String source = "" + "@Fnord(pi = 3.14, e = m*c*c)\n" + "public interface Foo extends Bar {\n" + " @Fnord(pi = 3.14, e = m*c*c)\n" + " void doStuff() { }\n" + "}\n"; builder.addSource(new StringReader(source)); assertEquals("Foo", builder.getClassByName("Foo").getName()); } public void testShouldIgnoreSingleMemberClassAnnotations() { String source = "" + "@Fnord(\"xyz\")\n" + "@Blat(Math.MAXINT)\n" + "public interface Foo extends Bar {\n" + " @Fnord(\"xyz\")\n" + " @Blat(Math.MAXINT)\n" + " void doStuff() { }\n" + "}\n"; builder.addSource(new StringReader(source)); assertEquals("Foo", builder.getClassByName("Foo").getName()); } public void testShouldIgnoreArrayValuedSingleMemberClassAnnotations() { String source = "" /** @hey=\"yo\" someval = \"yep\" */ + "@ Endorsers({(\"Children\"), \"Unscrupulous dentists\"})\n" + "public class Lollipop {\n" + " @Cheese( hey=@ano({\"Edam\", \"Gruyere\", 2}), t=5.5f, c=4)\n" + " void doStuff() { }\n" + "}\n"; builder.addSource(new StringReader(source)); assertNotNull(builder.getClassByName("Lollipop")); } public void testShouldIgnoreComplexSingleMemberClassAnnotations() { String source = "" + "@Author(@Name(first = \"Joe\", last = true))\n" // I won't take it personally! ;) -joe + "public class BitTwiddle {\n" + " @Author(@Name(first = \'c\', last = 2.5e3f))\n" + " void doStuff() { }\n" + "}\n"; builder.addSource(new StringReader(source)); assertNotNull(builder.getClassByName("BitTwiddle")); assertNotNull( builder.getClassByName("BitTwiddle").getAnnotations()[0].getNamedParameter("value") ); assertEquals( "Author", builder.getClassByName("BitTwiddle") .getMethodBySignature("doStuff", new Type[] {}) .getAnnotations()[0].getType().getValue() ); } public void testShouldIgnoreAnnotationDeclaration() { String source = "package org.jabba;\n" + "@MyAnno\n" + "public @interface Note {\n" + " String text;\n" + "}\n"; builder.addSource(new StringReader(source)); assertEquals(1, builder.getClasses().length); } public void testShouldIgnoreAnnotationWithClassType() { String source = "" + "@Fnord(String.class)\n" + "public interface Foo extends Bar {}\n"; builder.addSource(new StringReader(source)); assertEquals("Foo", builder.getClassByName("Foo").getName()); } // from QDOX-97 public void testShouldIgnoreAttributeAnnotation() { String source = "" + "public interface Foo {\n" + " String echo(@WebParam java.lang.String msg);\n" + "}\n"; builder.addSource(new StringReader(source)); assertEquals("Foo", builder.getClassByName("Foo").getName()); } // from QDOX-101 public void testShouldNotChokeOnDoubleAttributeAnnotationAndGenerics() { String source = "" + "public class Person {\n" + " @XmlJavaTypeAdapter(CollapsedStringAdapter.class)\n" + " @XmlID\n" + " protected String name;\n" + " public List getAddress() {\n" + " return address;\n" + " }" + "}\n"; builder.addSource(new StringReader(source)); assertEquals("Person", builder.getClassByName("Person").getName()); } // from QDOX-108 public void testFQNAnnotations() { String source = "" + "@com.mycompany.Fnord(a=1)\n" + "public interface Foo extends Bar {}\n"; builder.addSource(new StringReader(source)); assertEquals("Foo", builder.getClassByName("Foo").getName()); } // from QDOX-113 public void testAnnotationWithParameter() throws Exception { String source="public class Foo{\n" + "@Editor(FileEditor.class)\n" + "public void setFile(File file) { this.file = file; }" + "}"; builder.addSource(new StringReader(source)); } //from QDOX-128 public void testQuotedStringAnnotation() throws Exception { String source = "@Anno(run = \"1.0\")"+ "public interface Foo {}"; builder.addSource(new StringReader(source)); assertEquals("\"1.0\"", builder.getClassByName("Foo").getAnnotations()[0].getProperty("run").getParameterValue()); } // from QDOX-135 public void testAnnotationInMethodParamList() { String source = "" + "class Foo {\n" + " @X()\n" + " public String xyz(@Y(1) int blah) {\n" + " }\n" + "}\n"; builder.addSource(new StringReader(source)); JavaClass clazz = builder.getClassByName("Foo"); JavaMethod mth = clazz.getMethods()[0]; assertEquals("Foo", clazz.getName()); assertEquals("X", mth.getAnnotations()[0].getType().getJavaClass().getName()); } // from QDOX-142 public void testEmptyParameterListAnnotation() throws Exception { String source = "@MyAnnotation()\n" + "public class MyClass {}"; builder.addSource(new StringReader(source)); assertEquals("MyAnnotation", builder.getClasses()[0].getAnnotations()[0].getType().getValue()); } public void testMethodAnnotationBeforeComment() throws Exception { String source = "class Foo {\n" + "@Override\n" + "/**\n" + " * " + " */" + " public boolean isPostback() { return true;}\n" + "}"; builder.addSource(new StringReader(source)); assertEquals("java.lang.Override", builder.getClasses()[0].getMethods()[0].getAnnotations()[0].getType().getValue()); } public void testEnumsWithAnnotations() throws Exception { String source="class Foo {\n" + " public enum BasicType {\n" + " @XmlEnumValue(\"text\")\n" + " TEXT(\"text\"),\n" + "" + " @XmlEnumValue(\"value\")\n" + " VALUE(\"value\") }\n" + "}"; builder.addSource(new StringReader(source)); } public void testParameterAnnotations() throws Exception { String source = "class Foo {\n" + " @NativeAccessible\n" + " static void get_tmp_dir( String targetfilename, @ParamInfo( direction = ParamInfo.Direction.OUT ) byte[] tmpDirOutput ) throws IOException {}\n" + "}"; builder.addSource( new StringReader( source ) ); JavaMethod jMethod = builder.getClasses()[0].getMethods()[0]; assertEquals( "NativeAccessible", jMethod.getAnnotations()[0].getType().getValue() ); Annotation annotation = jMethod.getParameters()[1].getAnnotations()[0]; assertEquals( "ParamInfo", annotation.getType().getValue() ); assertEquals( "ParamInfo.Direction.OUT", annotation.getProperty( "direction" ).getParameterValue() ); } public void testFieldRefAnnotation() throws Exception { String source = "public class Foo {\n" + " final String s = \"unchecked\";\n" + " @SuppressWarnings( s )\n" + " public void testNothing() { }\n " + "}"; builder.addSource( new StringReader( source ) ); JavaMethod method = builder.getClasses()[0].getMethods()[0]; AnnotationFieldRef suppressWarnings = (AnnotationFieldRef) method.getAnnotations()[0].getProperty( "value" ); assertEquals( builder.getClasses()[0].getFields()[0], suppressWarnings.getField()); } public void testDoubleEscapedString() throws Exception { JavaDocBuilder builder = new JavaDocBuilder(); String source = "public class Foo {\n" + "@SuppressWarnings({\"abc\\\\d\"})\n" + "private void bar() { } }"; builder.addSource( new StringReader(source) ); } } qdox-qdox-1.12.1/src/test/com/thoughtworks/qdox/ClassResolutionTest.java000066400000000000000000000063121204551233600264260ustar00rootroot00000000000000package com.thoughtworks.qdox; import java.io.StringReader; import junit.framework.TestCase; import com.thoughtworks.qdox.model.JavaClass; import com.thoughtworks.qdox.model.JavaMethod; import com.thoughtworks.qdox.model.JavaParameter; import com.thoughtworks.qdox.model.Type; public class ClassResolutionTest extends TestCase { public void testNestedClassesResolvedAcrossPackageBoundaries() { // input sources String source1 = "" + "package package1;" + "public class Class1 {" + " public static final class NestedClass {}" + "}"; String source2 = "" + "package package2;" + "import package1.Class1;" + "public class Class2 {" + " public void doStuff(Class1.NestedClass arg) {}" + "}"; // parse JavaDocBuilder builder = new JavaDocBuilder(); builder.addSource(new StringReader(source1)); builder.addSource(new StringReader(source2)); // find the parameter JavaClass class2 = builder.getClassByName("package2.Class2"); JavaMethod method = class2.getMethods()[0]; JavaParameter parameter = method.getParameters()[0]; Type type = parameter.getType(); // verify assertEquals("Should include fully qualified name", "package1.Class1$NestedClass", type.getFullyQualifiedName()); } public void testSurvivesStaticImports() { // input sources String source = "" + "package package2;" + "import static package1.Class1.VALUE;" + "public class Class2 {" + " public void doStuff(String arg) {}" + "}"; // parse JavaDocBuilder builder = new JavaDocBuilder(); builder.addSource(new StringReader(source)); // find the parameter JavaClass class2 = builder.getClassByName("package2.Class2"); assertNotNull(class2); } public void testAnonymousClass() { JavaDocBuilder builder = new JavaDocBuilder(); String source = "" + "public class AnimatedAlgorithm {\n" + " private SelectionListener mySelectionListener = new SelectionListenerAdapter() {\n" + " public void selectionEvent() {\n" + " for (int i = 0; i < recalcers.size(); i++) {\n" + " int something = 5;" + " }\n" + " }\n" + " };\n" + "}"; builder.addSource(new StringReader(source)); } //from QDOX-86 public void testInnerClassInMethod() throws Exception { JavaDocBuilder builder = new JavaDocBuilder(); String source = "package some.pack;\n" + "class Test {\n" + "void some(Inner.Inner2 a) {}\n" + "static interface Inner {\n" + "static interface Inner2 { }\n" + "}\n" + "}"; builder.addSource(new StringReader(source)); JavaMethod method = builder.getClassByName("some.pack.Test").getMethods()[0]; JavaParameter parameter = method.getParameters()[0]; assertEquals("some.pack.Test$Inner$Inner2", parameter.getType().getJavaClass().getFullyQualifiedName()); } } qdox-qdox-1.12.1/src/test/com/thoughtworks/qdox/EnumsModelTest.java000066400000000000000000000176531204551233600253570ustar00rootroot00000000000000package com.thoughtworks.qdox; import junit.framework.TestCase; import java.io.StringReader; import com.thoughtworks.qdox.model.JavaClass; import com.thoughtworks.qdox.model.JavaField; public class EnumsModelTest extends TestCase { // These tests verify that we can access enum fields in the model. // This is a sequel to EnumsTest.java. public void testAddEmptyEnumsToModel() { String source = "" + "public enum Enum1 {}\n" + "enum Enum2 {;}\n"; JavaDocBuilder javaDocBuilder = new JavaDocBuilder(); javaDocBuilder.addSource(new StringReader(source)); JavaClass enum1 = javaDocBuilder.getClassByName("Enum1"); assertTrue(enum1.isEnum()); JavaClass enum2 = javaDocBuilder.getClassByName("Enum2"); assertTrue(enum2.isEnum()); } public void testAddSimpleEnumsToModel() { String source = "" + "public enum Enum1 { a, b }" + "class X { " + " enum Enum2 { c, /** some doc */ d } " + " int someField; " + "}"; JavaDocBuilder javaDocBuilder = new JavaDocBuilder(); javaDocBuilder.addSource(new StringReader(source)); JavaClass cls = javaDocBuilder.getClassByName("X"); assertEquals("int", cls.getFieldByName("someField").getType().getValue()); // sanity check JavaClass enum1 = javaDocBuilder.getClassByName("Enum1"); assertTrue(enum1.isEnum()); JavaClass enum2 = javaDocBuilder.getClassByName("X$Enum2"); assertTrue(enum2.isEnum()); //--- JavaField fields1[] = enum1.getFields(); // printFields( fields1 ); assertEquals(2, fields1.length); JavaField enum1a = fields1[0]; assertNull( enum1a.getComment() ); assertEquals( 1, enum1a.getModifiers().length ); assertEquals( "public", enum1a.getModifiers()[0] ); assertEquals( 0, enum1a.getAnnotations().length ); assertEquals( "Enum1", enum1a.getType().toString() ); assertEquals( "a", enum1a.getName() ); //--- JavaField fields2[] = enum2.getFields(); // printFields( fields2 ); assertEquals(2, fields2.length); JavaField enum2d = fields2[1]; assertNotNull( enum2d.getComment() ); assertEquals( 0, enum2d.getModifiers().length ); assertEquals( 0, enum2d.getAnnotations().length ); assertEquals( "X$Enum2", enum2d.getType().getFullyQualifiedName() ); assertEquals( "d", enum2d.getName() ); //--- } public void testAddEnumImplementingInterfaceToModel() { String source = "" + "public enum Enum1 implements java.io.Serializable { a, b }"; JavaDocBuilder javaDocBuilder = new JavaDocBuilder(); javaDocBuilder.addSource(new StringReader(source)); JavaClass cls = javaDocBuilder.getClassByName("Enum1"); assertTrue(cls.isEnum()); assertTrue(cls.isA("java.io.Serializable")); } /* // // Annotations on enums are not supported as of QDox 1.7 (2008-11-12) // public void testAddEnumWithAnnotationToModel() { String source = "" + "public enum Enum1 implements java.io.Serializable { a, @Deprecated b }"; JavaDocBuilder javaDocBuilder = new JavaDocBuilder(); javaDocBuilder.addSource(new StringReader(source)); JavaClass cls = javaDocBuilder.getClassByName("Enum1"); assertTrue(cls.isEnum()); assertTrue(cls.isA("java.io.Serializable")); //--- JavaField fields[] = cls.getFields(); // printFields( fields ); assertEquals(2, fields.length); JavaField enum1b = fields[1]; assertNull( enum1b.getComment() ); assertEquals( 1, enum1b.getModifiers().length ); assertEquals( "public", enum1b.getModifiers()[0] ); assertEquals( 1, enum1b.getAnnotations().length ); assertEquals( "@java.lang.Deprecated()", enum1b.getAnnotations()[0].toString() ); assertEquals( "Enum1", enum1b.getType().toString() ); assertEquals( "b", enum1b.getName() ); //--- } */ public void testAddEnumWithFieldAndConstructorsToModel() { String source = "" + "class X {\n" + " enum EnumWithConstructors {\n" + " c(\"hello\"), d();\n" + "\n" + " int someField;\n" + "\n" + " EnumWithConstructors() {}\n" + "\n" + " EnumWithConstructors(String x) {\n" + " }\n" + " }\n" + "}"; JavaDocBuilder javaDocBuilder = new JavaDocBuilder(); javaDocBuilder.addSource(new StringReader(source)); JavaClass cls = javaDocBuilder.getClassByName("X$EnumWithConstructors"); assertTrue(cls.isEnum()); assertEquals("int", cls.getFieldByName("someField").getType().getValue()); // sanity check //--- JavaField fields[] = cls.getFields(); // printFields( fields ); assertEquals(3, fields.length); // includes c, d, and someField JavaField enum1c = fields[0]; assertNull( enum1c.getComment() ); assertEquals( 0, enum1c.getModifiers().length ); assertEquals( 0, enum1c.getAnnotations().length ); assertEquals( "X$EnumWithConstructors", enum1c.getType().getFullyQualifiedName() ); assertEquals( "c", enum1c.getName() ); //--- JavaField enum1d = fields[1]; assertNull( enum1d.getComment() ); assertEquals( 0, enum1d.getModifiers().length ); assertEquals( "X$EnumWithConstructors", enum1d.getType().getFullyQualifiedName() ); assertEquals( "d", enum1d.getName() ); //--- } public void testAddEnumsWithMethodsToModel() throws Exception { String source = "" + "public enum Animal {\n" + " \n" + " DUCK { public void speak() { System.out.println(\"quack!\"); } },\n" + " CHICKEN { public void speak() { System.out.println(\"cluck!\"); } };\n" + "\n" + " public abstract void speak();\n" + "}"; JavaDocBuilder javaDocBuilder = new JavaDocBuilder(); javaDocBuilder.addSource(new StringReader(source)); JavaClass cls = javaDocBuilder.getClassByName("Animal"); assertTrue(cls.isEnum()); } //for qdox-118 public void testEnumWithJavaDocAndAnnotation() { String source = "public enum TestEnum\n" + "{\n" + "/**\n" + "* Blah blah\n" + "*/\n" + "@MyAnno\n" + "TEST;\n" + "}\n"; JavaDocBuilder javaDocBuilder = new JavaDocBuilder(); javaDocBuilder.addSource(new StringReader(source)); } /* private void printFields(final JavaField fields[]) { for(int i=0; iJoe Walnes * @author Aslak Hellesøy * @author Mike Williams */ public class GenericsTest extends TestCase { private JavaDocBuilder builder = new JavaDocBuilder(); public void testShouldUnderstandSingleGenericClassDeclarations() { String source = "" + "public interface Foo extends Bar {}"; builder.addSource(new StringReader(source)); assertEquals("Foo", builder.getClassByName("Foo").getName()); } public void testShouldUnderstandMultipleGenericClassDeclarations() { String source = "" + "public interface Foo extends Bar {}"; builder.addSource(new StringReader(source)); assertEquals("Foo", builder.getClassByName("Foo").getName()); } public void testShouldUnderstandMultipleGenericsInMethodDeclarations() { String source = "" + "public interface Foo {" + " Bar zap(Zip r);" + "}"; builder.addSource(new StringReader(source)); assertEquals("Foo", builder.getClassByName("Foo").getName()); } public void testShouldUnderstandOuterAndInnerClassGenericsInMethodDeclarations() { String source = "" + " public interface Foo {\n" + " void zap(Outer.Inner arg);\n" + " }"; builder.addSource(new StringReader(source)); assertEquals("Foo", builder.getClassByName("Foo").getName()); } public void testShouldUnderstandMultipleGenericsInConstructorDeclarations() { String source = "" + "public class Bar {" + " public Bar(Zip r) {}" + "}"; builder.addSource(new StringReader(source)); assertEquals("Bar", builder.getClassByName("Bar").getName()); } public void testShouldUnderstandMultipleGenericsInFieldDeclarations() { String source = "" + "public class Bar {" + " private Foo foo;" + "}"; builder.addSource(new StringReader(source)); assertEquals("Bar", builder.getClassByName("Bar").getName()); } public void testShouldUnderstandNestedGenerics() { String source = "" + "public class Bar {" + " private List> listOfLists;" + "}"; builder.addSource(new StringReader(source)); assertEquals("Bar", builder.getClassByName("Bar").getName()); } public void testShouldUnderstandFullyQualifiedTypeArguments() { String source = "" + "public class Bar {" + " private List listOfDates;" + "}"; builder.addSource(new StringReader(source)); assertEquals("Bar", builder.getClassByName("Bar").getName()); } public void testShouldUnderstandBoundedTypeParameters() { String source = "" + "public class Bar {}"; builder.addSource(new StringReader(source)); assertEquals("Bar", builder.getClassByName("Bar").getName()); } public void testShouldUnderstandComplexBoundedTypeParameters() { String source = "" + "public class Bar {}"; builder.addSource(new StringReader(source)); assertEquals("Bar", builder.getClassByName("Bar").getName()); } public void testShouldUnderstandWildcardTypeArguments() { String source = "" + "public class Bar { private Class klass; }"; builder.addSource(new StringReader(source)); assertEquals("Bar", builder.getClassByName("Bar").getName()); } public void testShouldUnderstandBoundedWildcardTypeArguments() { String source = "" + "public class Bar { Map klass; }"; builder.addSource(new StringReader(source)); assertEquals("Bar", builder.getClassByName("Bar").getName()); } public void testShouldUnderstandMethodTypeParameters() { String source = "" + "public class Bar {" + " public static > T max(Collection collection) {" + " throw new UnsupportedOperationException();" + " }" + "}"; builder.addSource(new StringReader(source)); assertEquals("Bar", builder.getClassByName("Bar").getName()); } public void testGenericField() { // Also see QDOX-77 String source = "" + "public class Foo {\n" + " protected Map m_env = new HashMap();\n" + " public Object retrieve(Class klass, Object key) {\n" + " return x;\n" + " }\n" + "}\n"; builder.addSource(new StringReader(source)); JavaClass fooClass = builder.getClassByName("Foo"); assertNotNull(fooClass); assertEquals("Foo", fooClass.getName()); JavaField envField = fooClass.getFieldByName("m_env"); assertNotNull(envField); assertEquals("Map", envField.getType().getValue()); } public void testGenericFieldInstantiation() { // Also see QDOX-77 String source = "" + "public class Foo {\n" + " protected Map m_env = new HashMap();\n" + " public Object retrieve(Class klass, Object key) {\n" + " return x;\n" + " }\n" + "}\n"; builder.addSource(new StringReader(source)); JavaClass fooClass = builder.getClassByName("Foo"); assertNotNull(fooClass); assertEquals("Foo", fooClass.getName()); JavaField envField = fooClass.getFieldByName("m_env"); assertNotNull(envField); assertEquals("Map", envField.getType().getValue()); } public void testGenericFieldInstantiationHalfComplex() { // Also see QDOX-77 String source = "" + "public class Foo {\n" + " protected Map, Object> m_env = new HashMap, Object>();\n" + " public Object retrieve(Class klass, Object key) {\n" + " return x;\n" + " }\n" + "}\n"; builder.addSource(new StringReader(source)); JavaClass fooClass = builder.getClassByName("Foo"); assertNotNull(fooClass); assertEquals("Foo", fooClass.getName()); JavaField envField = fooClass.getFieldByName("m_env"); assertNotNull(envField); assertEquals("Map", envField.getType().getValue()); } public void testGenericFieldInstantiationComplex() { // Also see QDOX-77 String source = "" + "public class Foo {\n" + " protected Map, Object> m_env = new HashMap, Object>();\n" + " public Object retrieve(Class klass, Object key) {\n" + " return x;\n" + " }\n" + "}\n"; builder.addSource(new StringReader(source)); JavaClass fooClass = builder.getClassByName("Foo"); assertNotNull(fooClass); assertEquals("Foo", fooClass.getName()); JavaField envField = fooClass.getFieldByName("m_env"); assertNotNull(envField); assertEquals("Map", envField.getType().getValue()); } public void testGenericFieldInstantiationVeryComplex() { // Also see QDOX-77 String source = "" + "public class Foo {\n" + " protected Map, ?>, Object> m_env = new HashMap, Object>, Object>();\n" + " public Object retrieve(Class klass, Object key) {\n" + " return x;\n" + " }\n" + "}\n"; builder.addSource(new StringReader(source)); JavaClass fooClass = builder.getClassByName("Foo"); assertNotNull(fooClass); assertEquals("Foo", fooClass.getName()); JavaField envField = fooClass.getFieldByName("m_env"); assertNotNull(envField); assertEquals("Map", envField.getType().getValue()); } public void testJiraQdox66() { // Also see QDOX-77 String source = "" + "public class Foo {\n" + " protected Map m_env = new HashMap();\n" + " public T retrieve(Class klass, Object key) {\n" + " return x;\n" + " }\n" + "}\n"; builder.addSource(new StringReader(source)); JavaClass fooClass = builder.getClassByName("Foo"); assertNotNull(fooClass); assertEquals("Foo", fooClass.getName()); JavaField envField = fooClass.getFieldByName("m_env"); assertNotNull(envField); assertEquals("Map", envField.getType().getValue()); } // QDOX-207 public void testMethodReturnTypeExtends() throws Exception { String superSource = "public abstract class Test {\n" + " private T me;\n" + " public Test(T me) {\n" + " this.me = me;\n" + " }\n" + " public T getValue() {\n" + " return me;\n" + " }\n" + " }"; String subSource = "public class StringTest extends Test {\n" + " public StringTest(String s) {\n" + " super(s);\n" + " }\n" + " }"; builder.addSource( new StringReader( superSource ) ); builder.addSource( new StringReader( subSource ) ); JavaMethod method = builder.getClassByName( "StringTest" ).getMethodBySignature( "getValue", null, true ); assertEquals( "T", method.getGenericReturnType().getFullyQualifiedName() ); assertEquals( "java.lang.Object", method.getReturnType().getFullyQualifiedName() ); assertEquals( "java.lang.Object", method.getReturnType( false ).getFullyQualifiedName() ); assertEquals( "java.lang.String", method.getReturnType( true ).getFullyQualifiedName() ); } public void testMethodReturnTypeImplements() throws Exception { String source1="public interface GenericDao {\n" + "public List getAll();\n" + "public TEntity getRandom();\n" + "public TEntity findById(TKey key);\n" + "public TEntity persist(TEntity entity);\n" + "public TEntity[] persist(TEntity[] entities);\n" + "public void delete(TEntity entity);\n" + "public Map asMap();" + "}\r\n"; String source2="public interface SubjectDao extends GenericDao {\n" + "public List getEnabledSubjects();\n" + "}\r\n"; String source3="public interface SubjectService extends RemoteService, SubjectDao {\r\n" + "}"; builder.addSource( new StringReader( source1 ) ); builder.addSource( new StringReader( source2 ) ); builder.addSource( new StringReader( source3 ) ); JavaMethod method = builder.getClassByName( "GenericDao" ).getMethodBySignature( "getRandom", null, true ); assertEquals( "TEntity", method.getReturnType( true ).getGenericValue() ); method = builder.getClassByName( "GenericDao" ).getMethodBySignature( "getAll", null, true ); assertEquals( "List", method.getReturnType( true ).getGenericValue() ); method = builder.getClassByName( "GenericDao" ).getMethodBySignature( "asMap", null, true ); assertEquals( "Map", method.getReturnType( true ).getGenericValue() ); method = builder.getClassByName( "SubjectDao" ).getMethodBySignature( "getRandom", null, true ); assertEquals( "Subject", method.getReturnType( true ).getGenericValue() ); method = builder.getClassByName( "SubjectDao" ).getMethodBySignature( "getAll", null, true ); assertEquals( "List", method.getReturnType( true ).getGenericValue() ); method = builder.getClassByName( "SubjectDao" ).getMethodBySignature( "asMap", null, true ); assertEquals( "Map", method.getReturnType( true ).getGenericValue() ); method = builder.getClassByName( "SubjectService" ).getMethodBySignature( "getRandom", null, true ); assertEquals( "Subject", method.getReturnType( true ).getGenericValue() ); method = builder.getClassByName( "SubjectService" ).getMethodBySignature( "getAll", null, true ); assertEquals( "List", method.getReturnType( true ).getGenericValue() ); method = builder.getClassByName( "SubjectService" ).getMethodBySignature( "asMap", null, true ); assertEquals( "Map", method.getReturnType( true ).getGenericValue() ); } //for QDOX-210 public void testResolveTypeGetMethod() throws Exception { String source1="import java.util.*;" + "public interface GenericDao {\n" + "public List getAll();\n" + "public TEntity getRandom();\n" + "public TEntity findById(TKey key);\n" + "public TEntity persist(TEntity entity);\n" + "public TEntity[] persist(TEntity[] entities);\n" + "public void delete(TEntity entity);\n" + "public Map asMap();" + "}\r\n"; String source2="public interface SubjectDao extends GenericDao {\n" + "}"; String source3="public interface SubjectService extends RemoteService, SubjectDao {\r\n" + "}"; builder.addSource( new StringReader( source1 ) ); builder.addSource( new StringReader( source2 ) ); builder.addSource( new StringReader( source3 ) ); JavaClass clazz = builder.getClassByName( "SubjectService" ); JavaMethod method = clazz.getMethods( true )[0]; assertEquals( "getAll", method.getName() ); assertEquals( "java.util.List", method.getReturnType( true ).getGenericValue() ); method = clazz.getMethods( true )[2]; assertEquals( "findById", method.getName() ); assertEquals( "java.lang.Long", method.getParameterTypes( true )[0].getGenericValue() ); } } qdox-qdox-1.12.1/src/test/com/thoughtworks/qdox/JSR14Test.java000066400000000000000000000515301204551233600241020ustar00rootroot00000000000000package com.thoughtworks.qdox; import java.io.StringReader; import java.lang.reflect.Method; import java.util.Collection; import java.util.List; import junit.framework.TestCase; import com.thoughtworks.qdox.model.JavaClass; import com.thoughtworks.qdox.model.JavaField; import com.thoughtworks.qdox.model.JavaMethod; import com.thoughtworks.qdox.model.JavaParameter; import com.thoughtworks.qdox.model.JavaSource; import com.thoughtworks.qdox.model.Type; /** * QDOX-54 Support for retrieval of generic type information (JSR 14) * * Some core-classes have been changed, but most interfaces are kept the same. * Most important is the method Type.getGenericValue(), which does exactly what it says. * The WildcardType is added as a subclass of Type. This way we can easily define these types of Types * * * @author Robert Scholte * */ public class JSR14Test extends TestCase { private JavaDocBuilder builder = new JavaDocBuilder(); public void testSimpleSingleParameterizedTypeMethod() throws Exception { JavaMethod javaMethod = buildMethod("java.util.List getList();"); assertEquals("java.util.List", javaMethod.getReturns().getGenericValue()); } public void testSimpleWildcardTypeMethod() throws Exception { JavaMethod javaMethod = buildMethod("java.util.List getList();"); assertEquals("java.util.List", javaMethod.getReturns().getGenericValue()); } public void testSimpleExtendsWildcardTypeMethod() throws Exception { JavaMethod javaMethod = buildMethod("java.util.List getList();"); assertEquals("java.util.List", javaMethod.getReturns().getGenericValue()); } public void testSimpleSuperWildcardTypeMethod() throws Exception { JavaMethod javaMethod = buildMethod("java.util.List getList();"); assertEquals("java.util.List", javaMethod.getReturns().getGenericValue()); } public void testSimpleMultiParameterizedTypeMethod() throws Exception { JavaMethod javaMethod = buildMethod("java.util.Map getMap();"); assertEquals("java.util.Map", javaMethod.getReturns().getGenericValue()); } public void testComplexSingleParameterizedTypeMethod() throws Exception { JavaMethod javaMethod = buildMethod("java.util.List> getList();"); assertEquals("java.util.List>", javaMethod.getReturns().getGenericValue()); } public void testComplexMultiParameterizedTypeMethod() throws Exception { JavaMethod javaMethod = buildMethod("java.util.Map> getMap();"); assertEquals("java.util.Map>", javaMethod.getReturns().getGenericValue()); } private JavaMethod buildMethod(String methodSource) { String source = "interface Something { " + methodSource + " }"; JavaSource javaSource = builder.addSource(new StringReader(source)); JavaClass javaClass = javaSource.getClasses()[0]; JavaMethod javaMethod = javaClass.getMethods()[0]; return javaMethod; } public void testSimpleSingleParameterizedTypeField() throws Exception { String source = "public class Something { " + "public java.util.List aList;" + " }"; JavaSource javaSource = builder.addSource(new StringReader(source)); JavaClass javaClass = javaSource.getClasses()[0]; JavaField javaField = javaClass.getFieldByName("aList"); assertEquals("java.util.List", javaField.getType().getGenericValue()); } public void testSimpleMultiParameterizedTypeField() { String source = "public class Something { " + "public java.util.Map aMap;" + " }"; JavaSource javaSource = builder.addSource(new StringReader(source)); JavaClass javaClass = javaSource.getClasses()[0]; JavaField javaField = javaClass.getFieldByName("aMap"); assertEquals("java.util.Map", javaField.getType().getGenericValue()); } public void testSimpleWildcardTypeField() throws Exception { String source = "public class Something { " + "public java.util.List aList;" + " }"; JavaSource javaSource = builder.addSource(new StringReader(source)); JavaClass javaClass = javaSource.getClasses()[0]; JavaField javaField = javaClass.getFieldByName("aList"); assertEquals("java.util.List", javaField.getType().getGenericValue()); } public void testSimpleExtendsWildcardTypeField() throws Exception { String source = "public class Something { " + "public java.util.List aList;" + " }"; JavaSource javaSource = builder.addSource(new StringReader(source)); JavaClass javaClass = javaSource.getClasses()[0]; JavaField javaField = javaClass.getFieldByName("aList"); assertEquals("java.util.List", javaField.getType().getGenericValue()); } public void testSimpleSuperWildcardTypeField() throws Exception { String source = "public class Something { " + "public java.util.List aList;" + " }"; JavaSource javaSource = builder.addSource(new StringReader(source)); JavaClass javaClass = javaSource.getClasses()[0]; JavaField javaField = javaClass.getFieldByName("aList"); assertEquals("java.util.List", javaField.getType().getGenericValue()); } public void testComplexSingleParameterizedTypeField() throws Exception { String source = "public class Something { " + "public java.util.List> aList;" + " }"; JavaSource javaSource = builder.addSource(new StringReader(source)); JavaClass javaClass = javaSource.getClasses()[0]; JavaField javaField = javaClass.getFieldByName("aList"); assertEquals("java.util.List>", javaField.getType().getGenericValue()); } public void testComplexMultiParameterizedTypeField() throws Exception { String source = "public class Something { " + "public java.util.List> aList;" + " }"; JavaSource javaSource = builder.addSource(new StringReader(source)); JavaClass javaClass = javaSource.getClasses()[0]; JavaField javaField = javaClass.getFieldByName("aList"); assertEquals("java.util.List>", javaField.getType().getGenericValue()); } public void testSimpleSingleParameterizedTypeParameter() throws Exception { JavaMethod javaMethod = buildMethod("void setList(java.util.List aList);"); assertEquals("java.util.List", javaMethod.getParameterByName("aList").getType().getGenericValue()); } public void testSimpleWildcardTypeParameter() throws Exception { JavaMethod javaMethod = buildMethod("void setList(java.util.List aList);"); assertEquals("java.util.List", javaMethod.getParameterByName("aList").getType().getGenericValue()); } public void testSimpleExtendsWildcardTypeParameter() throws Exception { JavaMethod javaMethod = buildMethod("void setList(java.util.List aList);"); assertEquals("java.util.List", javaMethod.getParameterByName("aList").getType().getGenericValue()); } public void testSimpleSuperWildcardTypeParameter() throws Exception { JavaMethod javaMethod = buildMethod("void setList(java.util.List aList);"); assertEquals("java.util.List", javaMethod.getParameterByName("aList").getType().getGenericValue()); } public void testSimpleMultiParameterizedTypeParameter() throws Exception { JavaMethod javaMethod = buildMethod("void setMap(java.util.Map aMap);"); assertEquals("java.util.Map", javaMethod.getParameterByName("aMap").getType().getGenericValue()); } public void testComplexSingleParameterizedTypeParameter() throws Exception { JavaMethod javaMethod = buildMethod("void setList(java.util.List> aList);"); assertEquals("java.util.List>", javaMethod.getParameterByName("aList").getType().getGenericValue()); } public void testComplexMultiParameterizedTypeParameter() throws Exception { JavaMethod javaMethod = buildMethod("void setMap(java.util.Map> aMap);"); assertEquals("java.util.Map>", javaMethod.getParameterByName("aMap").getType().getGenericValue()); } public void testSimpleSingleParameterizedTypeClassExtends() throws Exception { String source = "public class Something extends java.util.List {}"; JavaSource javaSource = builder.addSource(new StringReader(source)); JavaClass javaClass = javaSource.getClasses()[0]; Type superClass = javaClass.getSuperClass(); assertEquals("java.util.List", superClass.getGenericValue()); } public void testSimpleMultiParameterizedTypeClassExtends() { String source = "public class Something extends java.util.Map {}"; JavaSource javaSource = builder.addSource(new StringReader(source)); JavaClass javaClass = javaSource.getClasses()[0]; Type superClass = javaClass.getSuperClass(); assertEquals("java.util.Map", superClass.getGenericValue()); } public void testSimpleWildcardTypeClassExtends() throws Exception { String source = "public class Something extends java.util.List{}"; JavaSource javaSource = builder.addSource(new StringReader(source)); JavaClass javaClass = javaSource.getClasses()[0]; Type superClass = javaClass.getSuperClass(); assertEquals("java.util.List", superClass.getGenericValue()); } public void testSimpleExtendsWildcardTypeClassExtends() throws Exception { String source = "public class Something extends java.util.List {}"; JavaSource javaSource = builder.addSource(new StringReader(source)); JavaClass javaClass = javaSource.getClasses()[0]; Type superClass = javaClass.getSuperClass(); assertEquals("java.util.List", superClass.getGenericValue()); } public void testSimpleSuperWildcardTypeClassExtends() throws Exception { String source = "public class Something extends java.util.List {}"; JavaSource javaSource = builder.addSource(new StringReader(source)); JavaClass javaClass = javaSource.getClasses()[0]; Type superClass = javaClass.getSuperClass(); assertEquals("java.util.List", superClass.getGenericValue()); } public void testComplexSingleParameterizedTypeClassExtends() throws Exception { String source = "public class Something extends java.util.List> {}"; JavaSource javaSource = builder.addSource(new StringReader(source)); JavaClass javaClass = javaSource.getClasses()[0]; Type superClass = javaClass.getSuperClass(); assertEquals("java.util.List>", superClass.getGenericValue()); } public void testComplexMultiParameterizedTypeClassExtends() throws Exception { String source = "public class Something extends java.util.List> {}"; JavaSource javaSource = builder.addSource(new StringReader(source)); JavaClass javaClass = javaSource.getClasses()[0]; Type superClass = javaClass.getSuperClass(); assertEquals("java.util.List>", superClass.getGenericValue()); } public void testSimpleSingleParameterizedTypeClassImplements() throws Exception { String source = "public class Something implements java.util.List {}"; JavaSource javaSource = builder.addSource(new StringReader(source)); JavaClass javaClass = javaSource.getClasses()[0]; Type implementsClass = javaClass.getImplements()[0]; assertEquals("java.util.List", implementsClass.getGenericValue()); } public void testSimpleMultiParameterizedTypeClassImplements() { String source = "public class Something implements java.util.Map {}"; JavaSource javaSource = builder.addSource(new StringReader(source)); JavaClass javaClass = javaSource.getClasses()[0]; Type implementsClass = javaClass.getImplements()[0]; assertEquals("java.util.Map", implementsClass.getGenericValue()); } public void testSimpleWildcardTypeClassImplements() throws Exception { String source = "public class Something implements java.util.List{}"; JavaSource javaSource = builder.addSource(new StringReader(source)); JavaClass javaClass = javaSource.getClasses()[0]; Type implementsClass = javaClass.getImplements()[0]; assertEquals("java.util.List", implementsClass.getGenericValue()); } public void testSimpleExtendsWildcardTypeClassImplements() throws Exception { String source = "public class Something implements java.util.List {}"; JavaSource javaSource = builder.addSource(new StringReader(source)); JavaClass javaClass = javaSource.getClasses()[0]; Type implementsClass = javaClass.getImplements()[0]; assertEquals("java.util.List", implementsClass.getGenericValue()); } public void testSimpleSuperWildcardTypeClassImplements() throws Exception { String source = "public class Something implements java.util.List {}"; JavaSource javaSource = builder.addSource(new StringReader(source)); JavaClass javaClass = javaSource.getClasses()[0]; Type implementsClass = javaClass.getImplements()[0]; assertEquals("java.util.List", implementsClass.getGenericValue()); } public void testComplexSingleParameterizedTypeClassImplements() throws Exception { String source = "public class Something implements java.util.List> {}"; JavaSource javaSource = builder.addSource(new StringReader(source)); JavaClass javaClass = javaSource.getClasses()[0]; Type implementsClass = javaClass.getImplements()[0]; assertEquals("java.util.List>", implementsClass.getGenericValue()); } public void testComplexMultiParameterizedTypeClassImplements() throws Exception { String source = "public class Something implements java.util.List> {}"; JavaSource javaSource = builder.addSource(new StringReader(source)); JavaClass javaClass = javaSource.getClasses()[0]; Type implementsClass = javaClass.getImplements()[0]; assertEquals("java.util.List>", implementsClass.getGenericValue()); } public void testSimpleTypeVariable() throws Exception { String source = "public class Something {\n" + " public void doStuff(T param) {}\n" + "}"; JavaSource javaSource = builder.addSource(new StringReader(source)); JavaMethod javaMethod = javaSource.getClasses()[0].getMethods()[0]; assertEquals(1, javaMethod.getTypeParameters().length); assertEquals("java.lang.StringBuffer", javaMethod.getTypeParameters()[0].getValue()); assertEquals("", javaMethod.getTypeParameters()[0].getGenericValue()); } public void testComplexTypeVariable() throws Exception { String source = "class Collections {\n" + "public static void copy(List dest, List src){}\n" + "}"; JavaSource javaSource = builder.addSource(new StringReader(source)); JavaMethod javaMethod = javaSource.getClasses()[0].getMethods()[0]; assertEquals("T", javaMethod.getTypeParameters()[0].getName()); assertEquals("S", javaMethod.getTypeParameters()[1].getName()); assertEquals("T", javaMethod.getTypeParameters()[1].getValue()); } public void testComplexTypeVariableMultipleBounds() throws Exception { String source = "class Collections\n" + "public static >\n" + "T max(Collection coll) {\n" + "return null;}\n"; } //for qdox-150 // second assert is based on java's Method.toString() // http://java.sun.com/j2se/1.5.0/docs/api/java/lang/reflect/Method.html#toString() // 3rd and 4th are resolved Types, based on in method public void testGenericMethodDeclarationSingleParameter() throws Exception { String source = "package com.thoughtworks.qdox;" + "import java.util.*;\n" + "public class TestQDOX150 {\n" + " public List myMethod( T request ) throws Exception {\n" + " return null;\n" + " }\n" + "}\n"; JavaSource javaSource = builder.addSource(new StringReader(source)); JavaClass javaClass = javaSource.getClasses()[0]; JavaMethod javaMethod = javaClass.getMethods()[0]; JavaParameter paramType = javaMethod.getParameters()[0]; Type returnType = javaMethod.getReturns(); assertEquals("myMethod(request)", javaMethod.getCallSignature()); assertEquals("public java.util.List com.thoughtworks.qdox.TestQDOX150.myMethod(java.lang.StringBuffer) throws java.lang.Exception", javaMethod.toString()); assertEquals("java.lang.StringBuffer", paramType.getResolvedValue()); assertEquals("", paramType.getResolvedGenericValue()); assertEquals("java.util.List", returnType.getValue()); assertEquals("java.util.List", returnType.getGenericValue()); } public void testGenericMethodDeclarationMultipleParameters() throws Exception { String source = "package com.thoughtworks.qdox;" + "import java.util.*;\n" + "public class TestQDOX150 {\n" + " public List myMethod( T request, List list ) throws Exception {\n" + " return null;\n" + " }\n" + "}\n"; JavaSource javaSource = builder.addSource(new StringReader(source)); JavaClass javaClass = javaSource.getClasses()[0]; JavaMethod javaMethod = javaClass.getMethods()[0]; JavaParameter paramType = javaMethod.getParameters()[1]; assertEquals("myMethod(request, list)", javaMethod.getCallSignature()); assertEquals("public java.util.List com.thoughtworks.qdox.TestQDOX150.myMethod(java.lang.StringBuffer,java.util.List) throws java.lang.Exception", javaMethod.toString()); assertEquals("java.util.List", paramType.getResolvedValue()); assertEquals("java.util.List", paramType.getResolvedGenericValue()); } //for QDOX-167 public void testGenericTypedMethodCall() throws Exception { String source = "import java.util.*;\n" + "\n" + "public class MyClass\n" + "{\n" + "\n" + " private static final Map map1 = Collections.emptyMap();\n" + "\n" + " private static final Map map2 = Collections. emptyMap();\n" + "\n" + "}"; builder.addSource(new StringReader(source)); } // For QDox-205 public void testClassTypeParameters() throws Exception { String source1 = "class GenericControllerImpl>\n" + " implements GenericController\n {}"; String source2 = "class GroupControllerImpl extends\n" + " GenericControllerImpl\n {}"; String source3 = "interface GenericController {}"; builder.addSource(new StringReader(source1)); builder.addSource(new StringReader(source2)); builder.addSource(new StringReader(source3)); JavaClass genericControllerImpl = builder.getSources()[0].getClasses()[0]; assertEquals( 3, genericControllerImpl.getTypeParameters().length ); JavaClass groupControllerImpl = builder.getSources()[1].getClasses()[0]; assertEquals( 0, groupControllerImpl.getTypeParameters().length ); JavaClass genericController = builder.getSources()[2].getClasses()[0]; assertEquals( 2, genericController.getTypeParameters().length ); } // For QDOX-206 public void testGenericsAndArrays() throws Exception { JavaMethod method = buildMethod( "public Map test(Map input);" ); assertEquals("Map", method.getReturns().toGenericString()); assertEquals("Map", method.getParameters()[0].getType().toGenericString()); } } qdox-qdox-1.12.1/src/test/com/thoughtworks/qdox/JavaDocBuilderTest.java000066400000000000000000001477321204551233600261270ustar00rootroot00000000000000 package com.thoughtworks.qdox; import com.thoughtworks.qdox.model.*; import com.thoughtworks.qdox.model.util.SerializationUtils; import com.thoughtworks.qdox.parser.ParseException; import com.thoughtworks.qdox.testdata.PropertyClass; import java.io.*; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.Set; import java.util.HashSet; import org.jmock.Mock; import org.jmock.MockObjectTestCase; /** * @author Joe Walnes * @author Aslak Hellesøy */ public class JavaDocBuilderTest extends MockObjectTestCase { private JavaDocBuilder builder; protected void setUp() throws Exception { super.setUp(); builder = new JavaDocBuilder(); createFile("target/test-source/com/blah/Thing.java", "com.blah", "Thing"); createFile("target/test-source/com/blah/Another.java", "com.blah", "Another"); createFile("target/test-source/com/blah/subpackage/Cheese.java", "com.blah.subpackage", "Cheese"); createFile("target/test-source/com/blah/Ignore.notjava", "com.blah", "Ignore"); } protected void tearDown() throws Exception { super.tearDown(); deleteDir("target/test-source"); } public void testParsingMultipleJavaFiles() { builder.addSource(new StringReader(createTestClassList())); builder.addSource(new StringReader(createTestClass())); JavaSource[] sources = builder.getSources(); assertEquals(2, sources.length); JavaClass testClassList = sources[0].getClasses()[0]; assertEquals("TestClassList", testClassList.getName()); assertEquals("com.thoughtworks.util.TestClass", testClassList.getSuperClass().getValue()); JavaClass testClass = sources[1].getClasses()[0]; assertEquals("TestClass", testClass.getName()); JavaClass testClassListByName = builder.getClassByName("com.thoughtworks.qdox.TestClassList"); assertEquals("TestClassList", testClassListByName.getName()); JavaClass testClassByName = builder.getClassByName("com.thoughtworks.util.TestClass"); assertEquals("TestClass", testClassByName.getName()); } private String createTestClassList() { StringBuffer buffer = new StringBuffer(); buffer.append("package com.thoughtworks.qdox;"); buffer.append("import com.thoughtworks.util.*;"); buffer.append("public class TestClassList extends TestClass{"); buffer.append("private int numberOfTests;"); buffer.append("public int getNumberOfTests(){return numberOfTests;}"); buffer.append("public void setNumberOfTests(int numberOfTests){this.numberOfTests = numberOfTests;}"); buffer.append("}"); return buffer.toString(); } private String createTestClass() { StringBuffer buffer = new StringBuffer(); buffer.append("package com.thoughtworks.util;"); buffer.append("public class TestClass{"); buffer.append("public void test(){}"); buffer.append("}"); return buffer.toString(); } public void testParseWithInnerClass() { builder.addSource(new StringReader(createOuter())); JavaSource[] sources = builder.getSources(); assertEquals(1, sources.length); JavaClass outer = sources[0].getClasses()[0]; assertEquals("Outer", outer.getName()); assertEquals("foo.bar.Outer", outer.getFullyQualifiedName()); assertEquals(1, outer.getFields().length); assertEquals("int", outer.getFields()[0].getType().getValue()); assertEquals(1, outer.getMethods().length); assertEquals("outerMethod", outer.getMethods()[0].getName()); assertEquals(1, outer.getNestedClasses().length); JavaClass inner = outer.getNestedClasses()[0]; assertEquals("Inner", inner.getName()); assertEquals("foo.bar.Outer$Inner", inner.getFullyQualifiedName()); assertEquals(1, inner.getMethods().length); assertEquals("innerMethod", inner.getMethods()[0].getName()); } public void testGetClasses() { builder.addSource(new StringReader(createOuter())); JavaClass[] classes = builder.getClasses(); assertEquals(2, classes.length); } public void testGetPackagesShowsOnePackageAndTwoClasses() { builder.addSourceTree(new File("target/test-source")); JavaPackage[] packages = builder.getPackages(); assertEquals(2, packages.length); JavaPackage comBlahSubpackage = packages[0]; assertEquals("com.blah.subpackage", comBlahSubpackage.getName()); JavaPackage comBlah = packages[1]; assertEquals("com.blah", comBlah.getName()); JavaClass[] classes = comBlahSubpackage.getClasses(); assertEquals(1, classes.length); assertEquals("Cheese", classes[0].getName()); classes = comBlah.getClasses(); assertEquals(2, classes.length); assertEquals("Another", classes[0].getName()); assertEquals("Thing", classes[1].getName()); assertEquals(comBlah, comBlahSubpackage.getParentPackage()); assertNull(comBlah.getParentPackage()); JavaPackage[] comBlahSubpackages = comBlah.getSubPackages(); assertEquals(1, comBlahSubpackages.length); assertEquals(comBlahSubpackage, comBlahSubpackages[0]); JavaPackage[] comBlahSubpackageSubpackages = comBlahSubpackage.getSubPackages(); assertEquals(0, comBlahSubpackageSubpackages.length); } private String createOuter() { StringBuffer buffer = new StringBuffer(); buffer.append("package foo.bar;"); buffer.append("public class Outer {"); buffer.append(" private int numberOfTests;"); buffer.append(" class Inner {"); buffer.append(" public int innerMethod(){return System.currentTimeMillis();}"); buffer.append(" }"); buffer.append(" public void outerMethod(int count){}"); buffer.append("}"); return buffer.toString(); } public void testSourceTree() throws Exception { builder.addSourceTree(new File("target/test-source")); assertNotNull(builder.getClassByName("com.blah.Thing")); assertNotNull(builder.getClassByName("com.blah.Another")); assertNotNull(builder.getClassByName("com.blah.subpackage.Cheese")); } public void testRecordFile() throws Exception { builder.addSource(new File("target/test-source/com/blah/Thing.java")); JavaSource[] sources = builder.getSources(); assertEquals(1, sources.length); assertEquals(new File("target/test-source/com/blah/Thing.java").toURL(), sources[0].getURL()); } public void testSearcher() throws Exception { builder.addSourceTree(new File("target/test-source")); List results = builder.search(new Searcher() { public boolean eval(JavaClass cls) { return cls.getPackage().getName().equals("com.blah"); } }); assertEquals(2, results.size()); assertEquals("Another", ((JavaClass) results.get(0)).getName()); assertEquals("Thing", ((JavaClass) results.get(1)).getName()); } private void createFile(String fileName, String packageName, String className) throws Exception { File file = new File(fileName); file.getParentFile().mkdirs(); FileWriter writer = new FileWriter(file); writer.write("// this file generated by JavaDocBuilderTest - feel free to delete it\n"); writer.write("package " + packageName + ";\n\n"); writer.write("public class " + className + " {\n\n // empty\n\n}\n"); writer.close(); } private void deleteDir(String path) { File dir = new File(path); File[] children = dir.listFiles(); for (int i = 0; i < children.length; i++) { File file = children[i]; if (file.isDirectory()) { deleteDir(file.getAbsolutePath()); } else { file.delete(); } } dir.delete(); } public void testDefaultClassLoader() throws Exception { String in = "" + "package x;" + "import java.util.*;" + "import java.awt.*;" + "class X extends List {}"; builder.addSource(new StringReader(in)); JavaClass cls = builder.getClassByName("x.X"); assertEquals("java.util.List", cls.getSuperClass().getValue()); } public void testAddMoreClassLoaders() throws Exception { builder.getClassLibrary().addClassLoader(new ClassLoader() { public Class loadClass(String name) { return name.equals("com.thoughtworks.Spoon") ? this.getClass() : null; } }); builder.getClassLibrary().addClassLoader(new ClassLoader() { public Class loadClass(String name) { return name.equals("com.thoughtworks.Fork") ? this.getClass() : null; } }); String in = "" + "package x;" + "import java.util.*;" + "import com.thoughtworks.*;" + "class X {" + " Spoon a();" + " Fork b();" + " Cabbage c();" + "}"; builder.addSource(new StringReader(in)); JavaClass cls = builder.getClassByName("x.X"); assertEquals("com.thoughtworks.Spoon", cls.getMethods()[0].getReturns().getValue()); assertEquals("com.thoughtworks.Fork", cls.getMethods()[1].getReturns().getValue()); // unresolved assertEquals("Cabbage", cls.getMethods()[2].getReturns().getValue()); } public void testOldfashionedExtraClassesAreSupported() throws Exception { String in = "" + "package oldfashioned;" + "public class Ping {" + "}" + "class Bar {" + "}"; builder.addSource(new StringReader(in)); assertEquals(2, builder.getClasses().length); assertNotNull(builder.getClassByName("oldfashioned.Ping")); assertNotNull(builder.getClassByName("oldfashioned.Bar")); } public void testBinaryClassesAreFound() throws Exception { String in = "" + "package x;" + "import java.util.*;" + "class X {" + " ArrayList a();" + "}"; builder.addSource(new StringReader(in)); JavaClass cls = builder.getClassByName("x.X"); Type returnType = cls.getMethods()[0].getReturns(); JavaClass returnClass = builder.getClassByName(returnType.getValue()); assertEquals("java.util.ArrayList", returnClass.getFullyQualifiedName()); Type[] returnImplementz = returnClass.getImplements(); boolean foundList = false; for (int i = 0; i < returnImplementz.length; i++) { Type type = returnImplementz[i]; if (type.getValue().equals("java.util.List")) { foundList = true; } } assertTrue(foundList); // See if interfaces work too. JavaClass list = builder.getClassByName("java.util.List"); assertTrue(list.isInterface()); assertNull(list.getSuperJavaClass()); assertEquals("java.util.Collection", list.getImplements()[0].getValue()); } public void testSuperclassOfObjectIsNull() throws Exception { JavaClass object = builder.getClassByName("java.lang.Object"); JavaClass objectSuper = object.getSuperJavaClass(); assertNull(objectSuper); } /* Various test for isA. Tests interface extension, interface implementation and class extension. Immediate and chained. java.util.Collection | interface extension java.util.List | interface implemention java.util.AbstractList | class extension java.util.ArrayList */ public void testConcreteClassCanBeTestedForImplementedClassesAndInterfaces() { JavaClass arrayList = builder.getClassByName("java.util.ArrayList"); assertTrue("should be Object", arrayList.isA("java.lang.Object")); assertTrue("should be Collection", arrayList.isA("java.util.Collection")); assertTrue("should be List", arrayList.isA("java.util.List")); assertTrue("should be AbstractList", arrayList.isA("java.util.AbstractList")); assertTrue("should be ArrayList", arrayList.isA("java.util.ArrayList")); assertFalse("should not be Map", arrayList.isA("java.util.Map")); } public void testAbstractClassCanBeTestedForImplementedClassesAndInterfaces() { JavaClass abstractList = builder.getClassByName("java.util.AbstractList"); assertTrue("should be Object", abstractList.isA("java.lang.Object")); assertTrue("should be Collection", abstractList.isA("java.util.Collection")); assertTrue("should be List", abstractList.isA("java.util.List")); assertTrue("should be AbstractList", abstractList.isA("java.util.AbstractList")); assertFalse("should not be ArrayList", abstractList.isA("java.util.ArrayList")); assertFalse("should not be Map", abstractList.isA("java.util.Map")); } public void testInterfaceCanBeTestedForImplementedInterfaces() { JavaClass list = builder.getClassByName("java.util.List"); assertTrue("should be Collection", list.isA("java.util.Collection")); assertTrue("should be List", list.isA("java.util.List")); assertFalse("should not be ArrayList", list.isA("java.util.ArrayList")); assertFalse("should not be Map", list.isA("java.util.Map")); assertFalse("should not be Object", list.isA("java.lang.Object")); // I think! ;) } public void testClassCanBeTestedForNonexistantClasses() throws Exception { String in = "" + "package food;" + "class Sausage extends food.Meat implements food.Proteine {" + "}"; builder.addSource(new StringReader(in)); JavaClass sausage = builder.getClassByName("food.Sausage"); assertTrue(sausage.isA("food.Meat")); assertTrue(sausage.isA("food.Proteine")); } public void testClassesCanBeAddedLater() throws Exception { testClassCanBeTestedForNonexistantClasses(); assertEquals(1, builder.getClasses().length); JavaClass sausage = builder.getClassByName("food.Sausage"); assertFalse(sausage.isA("global.Stuff")); String in = "" + "package food;" + "class Meat extends global.Stuff {" + "}"; builder.addSource(new StringReader(in)); assertEquals(2, builder.getClasses().length); assertTrue(sausage.isA("global.Stuff")); } public void testImageIconBeanProperties() { JavaClass imageIcon = builder.getClassByName("javax.swing.ImageIcon"); assertNull(imageIcon.getBeanProperty("class")); BeanProperty clazz = imageIcon.getBeanProperty("class", true); assertNotNull(clazz.getAccessor()); assertNull(clazz.getMutator()); BeanProperty iconHeight = imageIcon.getBeanProperty("iconHeight"); assertNotNull(iconHeight.getAccessor()); assertNull(iconHeight.getMutator()); BeanProperty image = imageIcon.getBeanProperty("image"); assertNotNull(image.getAccessor()); assertNotNull(image.getMutator()); } public void testDerivedClassesAreFound() { /* Collection | interface extension List | interface implemention AbstractList | class extension ArrayList */ builder.addSource(new StringReader("public interface Collection {}")); builder.addSource(new StringReader("public interface List extends Collection {}")); builder.addSource(new StringReader("public class AbstractList implements List {}")); builder.addSource(new StringReader("public class ArrayList extends AbstractList {}")); JavaClass collection = builder.getClassByName("Collection"); JavaClass list = builder.getClassByName("List"); JavaClass abstractList = builder.getClassByName("AbstractList"); JavaClass arrayList = builder.getClassByName("ArrayList"); List derivedClassesOfCollection = Arrays.asList(collection.getDerivedClasses()); List derivedClassesOfList = Arrays.asList(list.getDerivedClasses()); List derivedClassesOfAbstractList = Arrays.asList(abstractList.getDerivedClasses()); List derivedClassesOfArrayList = Arrays.asList(arrayList.getDerivedClasses()); assertEquals(3, derivedClassesOfCollection.size()); assertEquals(2, derivedClassesOfList.size()); assertEquals(1, derivedClassesOfAbstractList.size()); assertEquals(0, derivedClassesOfArrayList.size()); } public void testSourcePropertyClass() throws IOException { builder.addSource(new File("src/test/com/thoughtworks/qdox/testdata/PropertyClass.java")); // Handy way to assert that behaviour for source and binary classes is the same. testPropertyClass(); } public void testPropertyClass() { JavaClass propertyClass = builder.getClassByName("com.thoughtworks.qdox.testdata.PropertyClass"); assertEquals(1, propertyClass.getBeanProperties().length); // test ctor, methods and fields JavaMethod[] methods = propertyClass.getMethods(); assertEquals(8, methods.length); JavaMethod ctor = propertyClass.getMethodBySignature("PropertyClass", null); JavaMethod ctor2 = propertyClass.getMethodBySignature("PropertyClass", new Type[] {propertyClass.asType()}); JavaMethod getFoo = propertyClass.getMethodBySignature("getFoo", null); JavaMethod isBar = propertyClass.getMethodBySignature("isBar", null); JavaMethod get = propertyClass.getMethodBySignature("get", null); JavaMethod set = propertyClass.getMethodBySignature("set", new Type[]{new Type("int")}); JavaMethod protectedMethod = propertyClass.getMethodBySignature("protectedMethod", null); JavaMethod privateMethod = propertyClass.getMethodBySignature("privateMethod", null); JavaMethod shouldntBeInherited = propertyClass.getMethodBySignature("getShouldntBeInherited", null); assertNotNull(ctor); assertNotNull(ctor2); assertNotNull(getFoo); assertNotNull(isBar); assertNotNull(get); assertNotNull(set); assertNotNull(protectedMethod); assertNotNull(privateMethod); assertNull(shouldntBeInherited); assertTrue(ctor.isConstructor()); assertTrue(ctor2.isConstructor()); assertFalse(getFoo.isConstructor()); assertFalse(isBar.isConstructor()); assertFalse(get.isConstructor()); assertFalse(set.isConstructor()); assertFalse(protectedMethod.isConstructor()); assertFalse(privateMethod.isConstructor()); assertTrue(getFoo.isStatic()); assertFalse(isBar.isStatic()); assertFalse(get.isStatic()); assertFalse(set.isStatic()); assertFalse(protectedMethod.isStatic()); assertFalse(privateMethod.isStatic()); assertTrue(get.isFinal()); assertFalse(set.isFinal()); assertTrue(ctor2.isProtected()); assertTrue(protectedMethod.isProtected()); assertTrue(privateMethod.isPrivate()); JavaField[] fields = propertyClass.getFields(); assertEquals(3, fields.length); } public void testSourceDefaultCtor() throws Exception { builder.addSource(new File("src/test/com/thoughtworks/qdox/testdata/DefaultCtor.java")); JavaClass javaClass = builder.getClassByName("com.thoughtworks.qdox.testdata.DefaultCtor"); JavaMethod ctor = javaClass.getMethodBySignature("DefaultCtor", null); // Differs from binary as currently no way to identify default // constructor in binary class. assertNull(ctor); } public void testBinaryDefaultCtor() { JavaClass javaClass = builder.getClassByName("com.thoughtworks.qdox.testdata.DefaultCtor"); JavaMethod ctor = javaClass.getMethodBySignature("DefaultCtor", null); // Differs from source as currently no way to identify default // constructor in binary class. assertNotNull(ctor); } public void testSerializable() throws Exception { builder.addSource(new StringReader("package test; public class X{}")); assertEquals("X", builder.getSources()[0].getClasses()[0].getName()); JavaDocBuilder newBuilder = (JavaDocBuilder) SerializationUtils.serializedCopy(builder); assertEquals("X", newBuilder.getSources()[0].getClasses()[0].getName()); } public void testSaveAndRestore() throws Exception { File file = new File("target/test-source/cache.obj"); builder.addSourceTree(new File("target/test-source")); builder.save(file); JavaDocBuilder newBuilder = JavaDocBuilder.load(file); assertNotNull(newBuilder.getClassByName("com.blah.subpackage.Cheese")); newBuilder.addSource(new StringReader("package x; import java.util.*; class Z extends List{}")); assertEquals("java.util.List", newBuilder.getClassByName("x.Z").getSuperClass().getValue()); } public void testSuperClassOfAnInterfaceReturnsNull() throws Exception { String in = "package x; interface I {}"; builder.addSource(new StringReader(in)); JavaClass cls = builder.getClassByName("x.I"); assertNull("Should probably return null", cls.getSuperJavaClass()); } public void testMethodsFromSuperclassesCanBeRetrieved() { String goodListSource = "" + "package x;" + "import java.util.*;" + "/**" + " * @foo bar" + " */" + "class GoodList extends ArrayList {" + " public void good() {}" + " private void myown() {}" + "}"; builder.addSource(new StringReader(goodListSource)); String betterListSource = "" + "package x;" + "/**" + " * @foo zap" + " */" + "class BetterList extends GoodList {" + " public void better() {}" + "}"; builder.addSource(new StringReader(betterListSource)); JavaClass betterList = builder.getClassByName("x.BetterList"); assertNull(betterList.getMethodBySignature("good", null)); assertNotNull(betterList.getMethodBySignature("good", null, true)); assertNotNull(betterList.getMethodBySignature("size", null, true)); assertNull("Shouldn't be able to get private methods", betterList.getMethodBySignature("myown", null, true)); } public void testTagLineNumbersAndSourceInTags() { String jallaSource = "" + "package x;\n" + "import java.util.*;\n" + "/**\n" + " * @line4 foo\n" + " * @line5 overflows onto\n" + " * line6\n" + " */\n" + "class Jalla extends ArrayList {\n" + "}\n"; builder.addSource(new StringReader(jallaSource)); JavaClass jalla = builder.getClassByName("x.Jalla"); DocletTag line4 = jalla.getTagByName("line4"); assertEquals(4, line4.getLineNumber()); assertSame(line4.getContext(), jalla); DocletTag line5 = jalla.getTagByName("line5"); assertEquals(5, line5.getLineNumber()); } public void testGetLineNumberForAbstractEntities() { String src = "" + "package x;\n" + "import java.util.*;\n" + "\n" + "class Foo {\n" + " int i;\n" + " int getI() { return i; }\n" + "}\n"; builder.addSource(new StringReader(src)); JavaClass fooClass = builder.getClassByName("x.Foo"); assertEquals(4, fooClass.getLineNumber()); JavaField iField = fooClass.getFieldByName("i"); assertEquals(5, iField.getLineNumber()); JavaMethod getIMethod = fooClass.getMethodBySignature("getI", Type.EMPTY_ARRAY); assertEquals(6, getIMethod.getLineNumber()); } public void testJiraQdox14() { String source = "" + "package foo; \n" + "class Outer { \n" + " Inner field1; \n" + " class Inner { \n" + " Outer.Inner field2; \n" + " } \n" + "} \n" + ""; builder.addSource(new StringReader(source)); JavaClass outer = builder.getClassByName("foo.Outer"); JavaClass inner = outer.getNestedClasses()[0]; assertEquals("foo.Outer$Inner", inner.getFullyQualifiedName()); JavaField field1 = outer.getFieldByName("field1"); Type type = field1.getType(); assertEquals("foo.Outer$Inner", type.getJavaClass().getFullyQualifiedName()); } public void testJiraQdox16() { String source = "" + "/**Hip hop won*t stop*/" + "class x{}"; builder.addSource(new StringReader(source)); JavaClass x = builder.getClassByName("x"); assertEquals("Hip hop won*t stop", x.getComment()); } public void testCommentsCanHaveNewlines() { String source = "" + "/** Hello\n" + "* world!" + "*/" + "class x{}"; builder.addSource(new StringReader(source)); JavaClass x = builder.getClassByName("x"); assertEquals("Hello\nworld!", x.getComment()); } public void testTagValuesCanSpanMultipleLines() { String source = "" + "/**\n" + " * @bar.baz foo=\"this is\\\n" + " * multilined\"\n" + " */\n" + "class x{}"; builder.addSource(new StringReader(source)); JavaClass x = builder.getClassByName("x"); DocletTag tag = x.getTagByName("bar.baz"); assertEquals("foo=\"this is\\\n multilined\"", tag.getValue()); assertEquals("this is\n multilined", tag.getNamedParameter("foo")); } public void testJiraQdox19() { String source = "" + "class x { \n" + " /**\n" + " * @y z\n" + " * \n" + " */\n" + " String m();\n" + "}\n" + ""; builder.addSource(new StringReader(source)); JavaClass x = builder.getClassByName("x"); JavaMethod m = x.getMethods()[0]; DocletTag foo = m.getTagByName("y"); assertEquals("z", foo.getValue()); } public void testTagInheritance() { String X = "" + "/** @c x */" + "class X {" + " /** \n" + " * @m x \n" + " * @s f\n" + " */" + " void i(){}" + "}"; String Y = "" + "/** @c y */" + "class Y extends X {" + " /** @m y */" + " void i(){}" + "}"; builder.addSource(new StringReader(X)); builder.addSource(new StringReader(Y)); JavaClass y = builder.getClassByName("Y"); DocletTag[] c = y.getTagsByName("c", true); assertEquals(2, c.length); assertEquals("y", c[0].getValue()); assertEquals("x", c[1].getValue()); JavaMethod i = y.getMethodBySignature("i", null); DocletTag[] m = i.getTagsByName("m", true); assertEquals(2, m.length); assertEquals("y", m[0].getValue()); assertEquals("x", m[1].getValue()); DocletTag s = i.getTagByName("s", true); assertEquals("f", s.getValue()); } public void testJiraQdox27() { String sourceCode = "" + "package com.acme.thing;\n" + "\n" + "/**" + " * This class does something." + " **/" + "public class AClassName {\n" + "}"; JavaDocBuilder builder = new JavaDocBuilder(); builder.addSource(new StringReader(sourceCode)); JavaClass aClass = builder.getClassByName("com.acme.thing.AClassName"); assertNotNull(aClass); } public void testJiraQdox39() { String sourceCode = "" + "public class A {\n" + " int i,j=2,k[];" + "}"; JavaDocBuilder builder = new JavaDocBuilder(); builder.addSource(new StringReader(sourceCode)); JavaClass a = builder.getClassByName("A"); assertEquals(3, a.getFields().length); assertEquals("i", a.getFields()[0].getName()); assertEquals("int", a.getFields()[0].getType().toString()); assertEquals("j", a.getFields()[1].getName()); assertEquals("int", a.getFields()[1].getType().toString()); assertEquals("k", a.getFields()[2].getName()); assertEquals("int[]", a.getFields()[2].getType().toString()); } public void testJiraQdox40() { String sourceCode = "" + "package foo.bar;" + "public class Outer {" + " class WrappedInternalContextAdapter implements InternalContextAdapter {" + " }" + "}"; JavaDocBuilder builder = new JavaDocBuilder(); builder.addSource(new StringReader(sourceCode)); JavaClass clazz = builder.getClassByName("foo.bar.Outer"); assertEquals(1, clazz.getNestedClasses().length); } public void testParseErrorLocationShouldBeAvailable() { String badSource = "" + "package x;\n" + "import java.util.*;\n" + "class Bad [\n"; try { builder.addSource(new StringReader(badSource)); fail("ParseException expected"); } catch (ParseException e) { assertEquals(3, e.getLine()); assertEquals(11, e.getColumn()); } } public void testJiraQdox35() { String sourceCode = "package pack; public class Foo extends Bar implements Zap {}"; JavaDocBuilder builder = new JavaDocBuilder(); builder.addSource(new StringReader(sourceCode)); JavaClass clazz = builder.getClassByName("pack.Foo"); assertEquals(1, clazz.getImplementedInterfaces().length); // Ideally the fully qualified names should be the pack.Zap and pack.Bar, // but this will do for now to fix the NPE bug. assertEquals("Zap", clazz.getImplementedInterfaces()[0].getFullyQualifiedName()); assertEquals("Bar", clazz.getSuperJavaClass().getFullyQualifiedName()); } /** * @french.english * cheese="fromage" * fish="poisson" * * @band.singer * doors=morrison * cure=smith */ public void testShouldShouldReportTagParameterKeys() { String sourceCode = "" + " /**\n" + " * @french.english\r\n" + " * cheese=\"fromage\"\n\r" + " * fish=\"poisson\"\r" + " */\n" + " class MultiLine{}"; JavaDocBuilder builder = new JavaDocBuilder(); JavaClass multiline = builder.addSource(new StringReader(sourceCode)).getClasses()[0]; DocletTag frenchEnglish = multiline.getTagByName("french.english"); Set expected = new HashSet(); expected.add("cheese"); expected.add("fish"); assertEquals(expected,frenchEnglish.getNamedParameterMap().keySet()); } public void testJiraQdox58() { builder.addSource(new StringReader( "class Y implements SomeInterface { }") ); List results = builder.search(new Searcher() { public boolean eval(JavaClass javaClass) { return javaClass.isA("SomeInterface"); } }); assertEquals(1, results.size()); } public void testJiraQdox63() { builder.addSource( new StringReader( "package p1;\n" + "class A {\n" + " static class Inner {}\n" + "}" ) ); builder.addSource( new StringReader( "package p2;\n" + "import p1.A;\n" + "class B {\n" + " A.Inner innerField;\n" + "}" ) ); JavaClass innerClass = builder.getClassByName("p1.A").getNestedClassByName("Inner"); JavaField innerField = builder.getClassByName("p2.B").getFieldByName("innerField"); assertEquals(innerClass.asType(), innerField.getType()); assertEquals("p1.A$Inner", innerField.getType().getFullyQualifiedName()); } public void testJiraQdox71() { String sourceCode = "" + "package foo;" + "public class C {" + " boolean flag = (X < Y);" + "}"; JavaDocBuilder builder = new JavaDocBuilder(); builder.addSource(new StringReader(sourceCode)); } public void testReadMultipleMethodAnnotations() { String sourceCode = "" + "public class C {" + " @Annotation\n" + " @AnotherAnnotation\n" + " public void aMethod() {}\n" + "}"; JavaDocBuilder builder = new JavaDocBuilder(); JavaSource javaSource = builder.addSource(new StringReader(sourceCode)); JavaMethod javaMethod = javaSource.getClasses()[0].getMethods()[0]; assertEquals("aMethod", javaMethod.getName()); } public void testReadMultipleClassAnnotations() { String sourceCode = "" + "@Annotation\n" + "@AnotherAnnotation\n" + "public class C {" + " public void aMethod() {}\n" + "}"; JavaDocBuilder builder = new JavaDocBuilder(); JavaSource javaSource = builder.addSource(new StringReader(sourceCode)); JavaClass javaClass = javaSource.getClasses()[0]; assertEquals("C", javaClass.getName()); } public void testMethodBody() { JavaDocBuilder builder = new JavaDocBuilder(); String sourceCode = "" + "public class X {\n" + " public void doStuff() {\n" + " System.out.println(\"hi\"); // comment\n" + " Foo x = new Cheese().get()[4]; /*x*/\n" + " } // not this \n" + "}"; JavaSource javaSource = builder.addSource(new StringReader(sourceCode)); JavaClass javaClass = javaSource.getClasses()[0]; JavaMethod javaMethod = javaClass.getMethods()[0]; String expected = "" + " System.out.println(\"hi\"); // comment\n" + " Foo x = new Cheese().get()[4]; /*x*/"; assertEquals(expected.trim(), javaMethod.getSourceCode().trim()); } public void testMethodBodyWithConfusingCurlies() { JavaDocBuilder builder = new JavaDocBuilder(); String sourceCode = "" + "public class X {\n" + " public void doStuff() {\n" + " System.out.println(\"}}} \\\"\"); // }\n" + " Foo x = new Cheese().get()[4]; /*}}*/ /etc\n" + " } // not this \n" + "}"; JavaSource javaSource = builder.addSource(new StringReader(sourceCode)); JavaClass javaClass = javaSource.getClasses()[0]; JavaMethod javaMethod = javaClass.getMethods()[0]; String expected = "" + " System.out.println(\"}}} \\\"\"); // }\n" + " Foo x = new Cheese().get()[4]; /*}}*/ /etc\n"; assertEquals(expected.trim(), javaMethod.getSourceCode().trim()); } public void testMethodBodyWithPrecedingStaticBlock() { JavaDocBuilder builder = new JavaDocBuilder(); String sourceCode = "" + "public class X {\n" + " static {\n" + " System.out.println(\"static\");\n" + " }\n" + " public void doStuff() {\n" + " System.out.println(\"hi\"); // comment\n" + " Foo x = new Cheese().get()[4]; /*x*/\n" + " } // not this \n" + "}"; JavaSource javaSource = builder.addSource(new StringReader(sourceCode)); JavaClass javaClass = javaSource.getClasses()[0]; JavaMethod javaMethod = javaClass.getMethods()[0]; String expected = "" + " System.out.println(\"hi\"); // comment\n" + " Foo x = new Cheese().get()[4]; /*x*/"; assertEquals(expected.trim(), javaMethod.getSourceCode().trim()); } public void testFieldDefinition() { JavaDocBuilder builder = new JavaDocBuilder(); String sourceCode = "" + "public class X {\n" + " int x = new FlubberFactory(\"}\"){}.doCheese(spam/*c*/)\n" + " [9] /*comment*/ //more\n; /*somethingelse*/" + "}"; JavaSource javaSource = builder.addSource(new StringReader(sourceCode)); JavaClass javaClass = javaSource.getClasses()[0]; JavaField javaField = javaClass.getFields()[0]; String expected = "" + "new FlubberFactory(\"}\"){}.doCheese(spam/*c*/)\n" + " [9] /*comment*/ //more"; assertEquals(expected.trim(), javaField.getInitializationExpression().trim()); } public void testNewlessArrays() { String source = "" + "public class Thing {\n" + " long[] bad = {1,2,3};\n" + // as opposed to bad = new long[] {1,2,3}. "}"; JavaDocBuilder builder = new JavaDocBuilder(); JavaSource javaSource = builder.addSource(new StringReader(source)); JavaField field = javaSource.getClasses()[0].getFieldByName("bad"); assertEquals("{1,2,3}", field.getInitializationExpression().trim()); } public void testDefaultsToThrowingExceptionWhenNotParseable() throws Exception { createFile("target/test-source/com/blah/Bad.java", "com.blah", "@%! BAD {}}}}"); JavaDocBuilder builder = new JavaDocBuilder(); try { builder.addSourceTree(new File("target/test-source")); fail("Expected exception"); } catch (ParseException expectedException) { // Good! } } public void testContinuesProcessingAfterBadFileIfCustomHandlerPermits() throws Exception { createFile("target/test-source/com/blah/Bad.java", "com.blah", "@%! BAD {}}}}"); Mock mockErrorHandler = mock(JavaDocBuilder.ErrorHandler.class); // Expectation mockErrorHandler.expects(once()) .method("handle") .with(isA(ParseException.class)); JavaDocBuilder builder = new JavaDocBuilder(); builder.setErrorHandler((JavaDocBuilder.ErrorHandler) mockErrorHandler.proxy()); builder.addSourceTree(new File("target/test-source")); assertNotNull(builder.getClassByName("com.blah.Thing")); } public void testBinaryClassFieldModifiers() { JavaDocBuilder builder = new JavaDocBuilder(); JavaClass javaClass = builder.getClassByName(PropertyClass.class.getName()); assertEquals("Class", PropertyClass.class.getName(), javaClass.getFullyQualifiedName()); JavaField javaField = javaClass.getFieldByName("aField"); assertNotNull("Field", javaField); Set modifiers = new HashSet(Arrays.asList(javaField.getModifiers())); assertEquals("Modifier count", 2, javaField.getModifiers().length); assertTrue("Static", modifiers.contains("static")); assertTrue("Public", modifiers.contains("public")); } public void testMultipleFieldsWithJavaDoc() throws Exception { String sourceCode = "class Thing {\n" + " /** some doc */\n" + " int a = 1,\n" + " /** more doc */\n" + " b = 2,\n" + " /** etc */\n" + " c = 3; }"; JavaDocBuilder builder = new JavaDocBuilder(); builder.addSource(new StringReader(sourceCode)); JavaClass javaClass = builder.getClasses()[0]; JavaField fieldA = javaClass.getFieldByName("a"); assertEquals("some doc", fieldA.getComment()); JavaField fieldB = javaClass.getFields()[1]; assertEquals("more doc", fieldB.getComment()); JavaField fieldC = javaClass.getFields()[2]; assertEquals("etc", fieldC.getComment()); } public void testJiraQdox117() throws Exception { JavaDocBuilder builder = new JavaDocBuilder(); String sourceCode = "" + "public class foo {\n" + "{ dosomething(); }\n" + "@Test (description=\"test blah blah\")\n" + "public void myTest() {}\n" + "}"; JavaSource javaSource = builder.addSource(new StringReader(sourceCode)); JavaClass javaClass = javaSource.getClasses()[0]; JavaMethod javaMethod = javaClass.getMethods()[0]; assertEquals("\"test blah blah\"", javaMethod.getAnnotations()[0].getNamedParameter("description").toString()); } public void testJiraQdox134() throws Exception { String sourceCode = "/**\n" + "*\n" + "@myTag name=TestClass attrs=Something1,Something2,Something3\n" + "*/\n" + "public class TestClassImpl {\r\n" + "}"; JavaDocBuilder builder = new JavaDocBuilder(); builder.addSource(new StringReader(sourceCode)); JavaClass jClass = builder.getClasses()[0]; assertEquals( Arrays.toString( new String[] {"name=TestClass","attrs=Something1,Something2,Something3"}), Arrays.toString(jClass.getTags()[0].getParameters())); //assertTrue( Arrays.equals( new String[] {"name=TestClass","attrs=Something1,Something2,Something3"}, jClass.getTags()[0].getParameters() )); } //for qdox-146 public void testWhitespaceCanBeRetainedInJavadoc() { String sourceCode = "" + "package com.acme.thing;\n" + "\n" + "/**\n" + " * This class does something.\n" + " * chalala\n" + " * cha ** lala\n" + " **/\n" + "public class AClassName {\n" + "}"; JavaDocBuilder builder = new JavaDocBuilder(); builder.addSource(new StringReader(sourceCode)); JavaClass aClass = builder.getClassByName("com.acme.thing.AClassName"); assertEquals("This class does something.\n" + " chalala\n" + " cha ** lala", aClass.getComment()); } //for qdox-152 public void testExtendedClass() throws Exception { String source = "import javax.faces.component.UIOutput;" + "public abstract class AbstractSayHello extends UIOutput {\n" + "}"; JavaSource javaSource = builder.addSource(new StringReader(source)); JavaClass javaClass = javaSource.getClasses()[0]; assertEquals(javaClass.getSuperClass().getValue(), "javax.faces.component.UIOutput"); } //for QDox-154 public void testImplicitJavadocCommentOrder() throws Exception { String source = "" + "public class Foo {\n" + " /**\n" + " * A Javadoc sample.\n" + " *\n" + " * @return The size.\n" + " */\n" + " public long getSize()\n" + " {\n" + " return 0;\n" + " }\n" + "\n" + " /**\n" + " * @return The size.\n" + " *\n" + " * A Javadoc sample.\n" + " */\n" + " public long getSize2()\n" + " {\n" + " return 0;\n" + " }\n" + "}"; JavaSource javaSource = builder.addSource(new StringReader(source)); JavaClass javaClass = javaSource.getClasses()[0]; JavaMethod method1 = javaClass.getMethods()[0]; assertEquals( "A Javadoc sample.", method1.getComment()); assertEquals( "The size.", method1.getTagByName( "return" ).getValue()); JavaMethod method2 = javaClass.getMethods()[1]; assertEquals( "The size.\n\nA Javadoc sample.", method2.getTagByName( "return" ).getValue()); } //for qdox-155 public void testCharField() throws Exception { String source = "public class Foo {\n" + "public static final char SEPARATOR = ',';" + "}"; JavaSource javaSource = builder.addSource(new StringReader(source)); JavaClass javaClass = javaSource.getClasses()[0]; assertEquals(javaClass.getFieldByName( "SEPARATOR" ).getInitializationExpression(), "','"); } //for qdox-157 public void testCommentBetweenFields() throws Exception { String source = "public class Foo {\n" + "public static final String TEST1 = \"test1\";\n" + "// TODO: blabla\n" + "public static final String TEST2 = \"test2\";\n" + "}"; JavaSource javaSource = builder.addSource(new StringReader(source)); JavaClass javaClass = javaSource.getClasses()[0]; assertEquals(javaClass.getFieldByName( "TEST2" ).getInitializationExpression(), "\"test2\""); } public void testAnnotationWithComment() throws Exception { String source = "@OneToMany(cascade = {/* CascadeType.PERSIST */}, fetch = FetchType.LAZY)\n" + "public class Foo{}"; JavaSource javaSource = builder.addSource(new StringReader(source)); JavaClass javaClass = javaSource.getClasses()[0]; assertNotNull(javaClass.getAnnotations()[0].getNamedParameter("cascade")); } /** * According to sun specs: Starting with Javadoc 1.4, the leading asterisks are optional * @throws Exception */ public void testJavadocWithoutStartingAsterisks() throws Exception { String source = " /**\n" + " Some text\n" + "more text\n" + "\t and even more\n" + " \n" + " @throws Exception\n" + "@deprecated" + " */\n" + "public class Foo{}"; JavaSource javaSource = builder.addSource(new StringReader(source)); JavaClass javaClass = javaSource.getClasses()[0]; assertEquals("Some text\nmore text\nand even more", javaClass.getComment()); assertEquals("throws", javaClass.getTags()[0].getName()); assertEquals("Exception", javaClass.getTags()[0].getValue()); assertEquals("deprecated", javaClass.getTags()[1].getName()); } // for QDOX-189 public void testFinalAnnotationParam() { JavaDocBuilder builder = new JavaDocBuilder(); String source = "public final class WSEndpointReference {\n" + " public void writeTo(final @NotNull String localName, @NotNull XMLStreamWriter w) throws XMLStreamException {\n" + " }\n" + "}"; builder.addSource(new StringReader(source)); } // for QDOX-190 public void testTwoCommentsBeforeEnumValue() { JavaDocBuilder builder = new JavaDocBuilder(); String source = "public enum Source {\n" + " /** comment 1 */ \n" + " /** comment 2 */\n" + " JDK1_2(\"1.2\");\n" + "}\n"; JavaSource src = builder.addSource(new StringReader(source)); assertEquals( "comment 2", src.getClasses()[0].getFieldByName( "JDK1_2" ).getComment() ); } //for QDOX-191 public void testLeftShift() { JavaDocBuilder builder = new JavaDocBuilder(); String source = "private static class Flags {\n" + " static final Flags LEFT_JUSTIFY = new Flags(1 << 0);\n" + "}\n"; builder.addSource(new StringReader(source)); } public void testGenericConstructor() { JavaDocBuilder builder = new JavaDocBuilder(); String source = "public class MXBeanSupport {\n" + " public MXBeanSupport(T resource, Class mxbeanInterface)\n" + " throws NotCompliantMBeanException {\n" + " } \n" + "}"; builder.addSource(new StringReader(source)); } // for QDOX-195 public void testSharedPackageJavaClasses() { String source1 = "@javax.xml.bind.annotation.XmlSchema(namespace = \"http://docs.oasis-open.org/wsn/br-2\")\n" + "package com.foo;\n" + "public class Bar1 {}"; String source2 = "package com.foo;\n" + "public class Bar2{}"; JavaSource javaSource1 = builder.addSource(new StringReader(source1)); JavaSource javaSource2 = builder.addSource(new StringReader(source2)); JavaPackage jPackage = builder.getPackageByName("com.foo"); assertEquals( 2, jPackage.getClasses().length ); assertEquals( 2, javaSource1.getPackage().getClasses().length ); assertEquals( 2, javaSource2.getPackage().getClasses().length ); assertNotSame( javaSource1.getPackage(), javaSource2.getPackage() ); assertEquals( 1, javaSource1.getPackage().getAnnotations().length ); assertEquals( 0, javaSource2.getPackage().getAnnotations().length ); assertEquals( 2, javaSource1.getPackage().getLineNumber() ); assertEquals( 1, javaSource2.getPackage().getLineNumber() ); } public void testSourceFolder() throws Exception { JavaDocBuilder builder = new JavaDocBuilder(); builder.getClassLibrary().addSourceFolder( new File("target/test-source") ); String source = "package com.foo;\n" + "import com.blah.*;\n" + "public abstract class Me {\n" + " public abstract Thing getThing(); " + "}"; builder.addSource( new StringReader( source ) ); JavaClass clazz = builder.addSource( new StringReader( source ) ).getClasses()[0]; JavaClass thing = clazz.getMethods()[0].getReturns().getJavaClass(); assertEquals("com.blah.Thing", thing.getFullyQualifiedName()); assertNotNull(thing.getSource()); } // for QDOX-208 public void testMethodLineNumber() throws Exception { JavaDocBuilder builder = new JavaDocBuilder(); String source = "package com.foo;\n" + "public class Bar {\n" + " public void method1() \n" + " {}\n" + "\n" + " /**\n" + " * Method with javadoc\n" + " */\n" + " public void method1() { \n" + " }\n" + "}"; builder.addSource( new StringReader( source ) ); JavaClass clazz = builder.getClasses()[0]; assertEquals( 3, clazz.getMethods()[0].getLineNumber() ); assertEquals( 9, clazz.getMethods()[1].getLineNumber() ); } // for QDOX-209 public void testAnnotationMap() throws Exception{ JavaDocBuilder javaDocBuilder = new JavaDocBuilder(); String source = "import javax.persistence.JoinColumn;\n" + "public class Instruction {\n" + " private static final int something = 40;\n" + " //-----------------------------------------------------------------------\r\n" + " @JoinColumn(name=\"test\",bla=\"hi\")\n" + " int testfield;\r\n" + "}"; javaDocBuilder.addSource(new StringReader( source )); JavaClass classByName = javaDocBuilder.getClassByName("Instruction"); JavaField fieldByName = classByName.getFieldByName("testfield"); Annotation[] annotations = fieldByName.getAnnotations(); // Now we do have the annotation "JoinColumn" in annotations[0] Map propertyMap = annotations[0].getNamedParameterMap(); // This one works assertEquals("\"hi\"", propertyMap.get("bla")); String string = (String) propertyMap.get("name"); // This one does not work assertEquals("\"test\"", string); } } qdox-qdox-1.12.1/src/test/com/thoughtworks/qdox/MethodsTest.java000066400000000000000000000041351204551233600247010ustar00rootroot00000000000000package com.thoughtworks.qdox; import com.thoughtworks.qdox.model.JavaClass; import com.thoughtworks.qdox.model.JavaMethod; import com.thoughtworks.qdox.model.JavaSource; import com.thoughtworks.qdox.model.Type; import com.thoughtworks.qdox.model.JavaParameter; import junit.framework.TestCase; import java.io.StringReader; public class MethodsTest extends TestCase { private JavaDocBuilder builder = new JavaDocBuilder(); public void testSupportsJava5VarArgsParameter() { JavaMethod javaMethod = buildMethod("void doStuff(AThing param1, BThing... param2);"); JavaParameter standardParam = javaMethod.getParameterByName("param1"); JavaParameter varArgsParam = javaMethod.getParameterByName("param2"); assertFalse("param1 should NOT be var args", standardParam.isVarArgs()); assertTrue("param2 should be var args", varArgsParam.isVarArgs()); } public void testVarArgsParametersAreAlsoArrays() { JavaMethod javaMethod = buildMethod("void doStuff(AThing param1, BThing[] param2, CThing... param3);"); Type standardType = javaMethod.getParameterByName("param1").getType(); Type arrayType = javaMethod.getParameterByName("param2").getType(); Type varArgsType = javaMethod.getParameterByName("param3").getType(); assertFalse("param1 should NOT be array", standardType.isArray()); assertTrue("param2 should be array", arrayType.isArray()); assertFalse("param3 should NOT be array", varArgsType.isArray()); } public void testVarArgsIncludedInToString() { JavaMethod javaMethod = buildMethod("void doStuff(AThing param1, BThing... param2);"); assertEquals("void doStuff(AThing param1, BThing... param2);\n", javaMethod.getCodeBlock()); } private JavaMethod buildMethod(String methodSource) { String source = "interface Something { " + methodSource + " }"; JavaSource javaSource = builder.addSource(new StringReader(source)); JavaClass javaClass = javaSource.getClasses()[0]; JavaMethod javaMethod = javaClass.getMethods()[0]; return javaMethod; } } qdox-qdox-1.12.1/src/test/com/thoughtworks/qdox/TestQDoxBug131.java000066400000000000000000000022061204551233600250310ustar00rootroot00000000000000package com.thoughtworks.qdox; import java.io.StringReader; import junit.framework.TestCase; import com.thoughtworks.qdox.model.JavaClass; public class TestQDoxBug131 extends TestCase { public void testname() throws Exception { String sourceCode = "package com.acme.qdox;\n" + "\n" + "public class QDoxBugClass {\n" + " final public static String C1 = \"C1\", C2 = \"C2\";\n" + " final public static String[] ALL = { C1, C2 }; \n" + " /*\n" + " Comment\n" + " */\n" + " public void method() {\n" + " System.out.println(\"This will contain the comment\");\n" + " }\n" + "}\n" + ""; JavaDocBuilder builder = new JavaDocBuilder(); builder.addSource(new StringReader(sourceCode)); JavaClass aClass = builder.getClassByName("com.acme.qdox.QDoxBugClass"); assertEquals("\n System.out.println(\"This will contain the comment\");\n ", aClass.getMethods()[0].getSourceCode()); } } qdox-qdox-1.12.1/src/test/com/thoughtworks/qdox/ant/000077500000000000000000000000001204551233600223525ustar00rootroot00000000000000qdox-qdox-1.12.1/src/test/com/thoughtworks/qdox/ant/AbstractQdoxTaskTest.java000066400000000000000000000106041204551233600273000ustar00rootroot00000000000000package com.thoughtworks.qdox.ant; import junit.framework.TestCase; import java.io.File; import org.apache.tools.ant.Project; import org.apache.tools.ant.DirectoryScanner; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.types.FileSet; import com.thoughtworks.qdox.model.*; // Not really abstract, but a test of the abstract. public class AbstractQdoxTaskTest extends TestCase { public AbstractQdoxTaskTest(String name) { super(name); } public void testBasic() throws Exception { OveriddenAbstractQdoxTask task = new OveriddenAbstractQdoxTask(); task.addFileset(new OveriddenFileSet("src/java", new String[]{"com/thoughtworks/qdox/directorywalker/SuffixFilter.java"})); task.execute(); JavaClass hopefullySuffixFilter = ((JavaClass) task.allClasses.get(0)); assertNotNull("Expected a JavaClass", task.allClasses.get(0)); assertEquals("SuffixFilter", hopefullySuffixFilter.getName()); assertEquals("com.thoughtworks.qdox.directorywalker.SuffixFilter", task.classes); } public void testPluggableTagFactory() { OwnTagFactoryUsingQdoxTask task = new OwnTagFactoryUsingQdoxTask(); task.execute(); } private class OwnTagFactoryUsingQdoxTask extends AbstractQdoxTask { public OwnTagFactoryUsingQdoxTask() { addFileset(new OveriddenFileSet("src/test", new String[]{"com/thoughtworks/qdox/testdata/PropertyClass.java"})); } protected DocletTagFactory createDocletTagFactory() { // Tag factory that returns tags with "aslak." prefixed to their "original" name. // Not useful at all, only to test that we can actually plug in any tag factory. return new DocletTagFactory() { public DocletTag createDocletTag(String tag, String text, AbstractBaseJavaEntity context, int lineNumber) { return new DefaultDocletTag("aslak." + tag, text); } public DocletTag createDocletTag(String tag, String text) { fail(); return null; } }; } public void execute() { super.execute(); JavaClass hopefullyPropertyClass = (JavaClass) allClasses.get(0); DocletTag hopefullyAslakDotFoo = hopefullyPropertyClass.getTagByName("aslak.foo"); assertNotNull(hopefullyAslakDotFoo); assertEquals("zap", hopefullyAslakDotFoo.getNamedParameter("bar")); } } public void testNoFileSets() { OveriddenAbstractQdoxTask task = new OveriddenAbstractQdoxTask(); try { task.execute(); fail("Expected an empty list of classes"); } catch (BuildException e) { // expected } } private class OveriddenAbstractQdoxTask extends AbstractQdoxTask { public String classes = ""; public void execute() { super.execute(); for (int i = 0; i < allClasses.size(); i++) { JavaClass javaClass = (JavaClass) allClasses.get(i); classes = classes + javaClass.getFullyQualifiedName(); // Interested in seeing output? Uncomment this. // System.out.println("Class:" + javaClass.getName()); } } } private class OveriddenFileSet extends FileSet { private OveridenDirectoryScanner overidenDirectoryScanner; private String dir; public OveriddenFileSet(String dir, String[] includedFiles) { this.dir = dir; overidenDirectoryScanner = new OveridenDirectoryScanner(includedFiles); } public File getDir(Project project) { return getUnderJUnitFile(dir); } public DirectoryScanner getDirectoryScanner(Project project) { return overidenDirectoryScanner; } } public static File getUnderJUnitFile(String filename) { File result = new File("../" + filename); if (result.exists()) return result; return new File(filename); } private class OveridenDirectoryScanner extends DirectoryScanner { private String[] includedFiles; public OveridenDirectoryScanner(String[] includedFiles) { this.includedFiles = includedFiles; } public String[] getIncludedFiles() { return includedFiles; } } } qdox-qdox-1.12.1/src/test/com/thoughtworks/qdox/directorywalker/000077500000000000000000000000001204551233600250025ustar00rootroot00000000000000qdox-qdox-1.12.1/src/test/com/thoughtworks/qdox/directorywalker/DirectoryScannerTest.java000066400000000000000000000126371204551233600317740ustar00rootroot00000000000000package com.thoughtworks.qdox.directorywalker; import java.io.File; import org.jmock.Mock; import org.jmock.MockObjectTestCase; public class DirectoryScannerTest extends MockObjectTestCase { class MockFile extends File { boolean isDirectory; File[] children; public MockFile(String pathname) { super(pathname); this.isDirectory = false; } public MockFile(String pathname, boolean isDirectory) { super(pathname); this.isDirectory = isDirectory; } public boolean isDirectory() { return this.isDirectory; } public File[] listFiles() { return children; } } public DirectoryScannerTest(String s) { super(s); } public void testSingleDirectory() { MockFile rootDir = new MockFile("root", true); rootDir.children = new File[]{new MockFile("blah.txt"), new MockFile("foo.txt"), new MockFile("pig.java")}; DirectoryScanner scanner = new DirectoryScanner(rootDir); File[] files = scanner.scan(); assertEquals(3, files.length); assertEquals("blah.txt", files[0].getName()); assertEquals("foo.txt", files[1].getName()); assertEquals("pig.java", files[2].getName()); } public void testDirectoryWithSubdir() { MockFile rootDir = new MockFile("root", true); MockFile subDir = new MockFile("subdir", true); subDir.children = new File[]{new MockFile("child1.txt"), new MockFile("child2.txt")}; rootDir.children = new File[]{subDir, new MockFile("foo.txt"), new MockFile("pig.java")}; DirectoryScanner scanner = new DirectoryScanner(rootDir); File[] files = scanner.scan(); assertEquals(4, files.length); assertEquals("child1.txt", files[0].getName()); assertEquals("child2.txt", files[1].getName()); assertEquals("foo.txt", files[2].getName()); assertEquals("pig.java", files[3].getName()); } public void testDirectoryWithSubdirWithSubdir() { MockFile rootDir = new MockFile("root", true); MockFile subDir1 = new MockFile("subdir", true); MockFile subDir2 = new MockFile("subdir2", true); subDir2.children = new File[]{new MockFile("grandChild1.txt")}; subDir1.children = new File[]{subDir2, new MockFile("child1.txt"), new MockFile("child2.txt")}; rootDir.children = new File[]{subDir1, new MockFile("foo.txt"), new MockFile("pig.java")}; DirectoryScanner scanner = new DirectoryScanner(rootDir); File[] files = scanner.scan(); assertEquals(5, files.length); assertEquals("grandChild1.txt", files[0].getName()); assertEquals("child1.txt", files[1].getName()); assertEquals("child2.txt", files[2].getName()); assertEquals("foo.txt", files[3].getName()); assertEquals("pig.java", files[4].getName()); } public void testSuffixFilter() { MockFile rootDir = new MockFile("root", true); rootDir.children = new File[]{new MockFile("blah.txt"), new MockFile("foo.java"), new MockFile("pig.java")}; DirectoryScanner scanner = new DirectoryScanner(rootDir); scanner.addFilter(new SuffixFilter(".java")); File[] files = scanner.scan(); assertEquals(2, files.length); assertEquals("foo.java", files[0].getName()); assertEquals("pig.java", files[1].getName()); } public void testFilterCallback() { MockFile rootDir = new MockFile("root", true); rootDir.children = new File[]{new MockFile("blah.txt"), new MockFile("foo.java"), new MockFile("pig.java")}; DirectoryScanner scanner = new DirectoryScanner(rootDir); Filter mockFilter = new Filter() { public boolean filter(File file) { return file.getName().equals("foo.java"); } }; scanner.addFilter(mockFilter); File[] files = scanner.scan(); assertEquals(1, files.length); assertEquals("foo.java", files[0].getName()); } public void testMultipleFilters() { MockFile rootDir = new MockFile("root", true); rootDir.children = new File[]{new MockFile("blah.txt"), new MockFile("foo.java"), new MockFile("pig.java"), new MockFile("foo.txt")}; DirectoryScanner scanner = new DirectoryScanner(rootDir); scanner.addFilter(new SuffixFilter(".java")); scanner.addFilter(new Filter() { public boolean filter(File file) { return file.getName().startsWith("foo"); } }); File[] files = scanner.scan(); assertEquals(1, files.length); assertEquals("foo.java", files[0].getName()); } public void testFileVisitor() { MockFile rootDir = new MockFile("root", true); rootDir.children = new File[]{new MockFile("blah.txt"), new MockFile("foo.txt"), new MockFile("pig.java")}; DirectoryScanner scanner = new DirectoryScanner(rootDir); Mock mockFileVisitor = new Mock(FileVisitor.class); mockFileVisitor.expects(once()).method("visitFile").with(same(rootDir.children[0])); mockFileVisitor.expects(once()).method("visitFile").with(same(rootDir.children[1])); mockFileVisitor.expects(once()).method("visitFile").with(same(rootDir.children[2])); scanner.scan((FileVisitor) mockFileVisitor.proxy()); mockFileVisitor.verify(); } } qdox-qdox-1.12.1/src/test/com/thoughtworks/qdox/model/000077500000000000000000000000001204551233600226705ustar00rootroot00000000000000qdox-qdox-1.12.1/src/test/com/thoughtworks/qdox/model/AbstractDocletTagTest.java000066400000000000000000000075231204551233600277340ustar00rootroot00000000000000package com.thoughtworks.qdox.model; import junit.framework.TestCase; import com.thoughtworks.qdox.JavaDocBuilder; import java.io.StringReader; import java.util.Map; public abstract class AbstractDocletTagTest extends TestCase { public AbstractDocletTagTest(String s) { super(s); } protected abstract DocletTagFactory getDocletTagFactory(); DocletTag createDocletTag(String tag, String text) { return getDocletTagFactory().createDocletTag(tag, text); } public void testValueRemainsIntact() throws Exception { String in = "" + "package x;\n" + "/**\n" + " * @tag aa count(*) bbb * ccc dd=e f='g' i = \"xx\"\n" + " */\n" + "class X {}"; JavaDocBuilder builder = new JavaDocBuilder(getDocletTagFactory()); builder.addSource(new StringReader(in)); DocletTag tag = builder.getClassByName("x.X").getTagByName("tag"); assertEquals("aa count(*) bbb * ccc dd=e f='g' i = \"xx\"", tag.getValue()); } public void testIndexedParameter() throws Exception { DocletTag tag = createDocletTag("x", "one two three four"); assertEquals("one", tag.getParameters()[0]); assertEquals("two", tag.getParameters()[1]); assertEquals("three", tag.getParameters()[2]); assertEquals("four", tag.getParameters()[3]); assertEquals(4, tag.getParameters().length); } public void testNamedParameter() throws Exception { DocletTag tag = getDocletTagFactory().createDocletTag( "x", "hello=world dog=cat fork=spoon" ); assertEquals("world", tag.getNamedParameter("hello")); assertEquals("cat", tag.getNamedParameter("dog")); assertEquals("spoon", tag.getNamedParameter("fork")); assertNull(tag.getNamedParameter("goat")); } public void testNamedParameterMap() throws Exception { DocletTag tag = createDocletTag( "x", "hello=world dog=cat fork=spoon" ); Map map = tag.getNamedParameterMap(); assertEquals(3, map.size()); assertEquals("world", map.get("hello")); assertEquals("cat", map.get("dog")); assertEquals("spoon", map.get("fork")); assertNull(map.get("goat")); } public void testQuotedParameters() throws Exception { DocletTag tag = createDocletTag("x", "one=\"hello world bye bye\" two=hello"); assertEquals("hello world bye bye", tag.getNamedParameter("one")); assertEquals("hello", tag.getNamedParameter("two")); tag = createDocletTag("x", "one=\"hello joe's world bye bye\" two=hello"); assertEquals("hello joe's world bye bye", tag.getNamedParameter("one")); assertEquals("hello", tag.getNamedParameter("two")); tag = createDocletTag("x", "one='hello joe\"s world bye bye' two=hello"); assertEquals("hello joe\"s world bye bye", tag.getNamedParameter("one")); assertEquals("hello", tag.getNamedParameter("two")); tag = createDocletTag("x", "one=\"hello chris' world bye bye\" two=hello"); assertEquals("hello chris' world bye bye", tag.getNamedParameter("one")); assertEquals("hello", tag.getNamedParameter("two")); } public void testJiraQdox28() { DocletTag tag = createDocletTag("key", "quote'ed"); assertEquals("quote", tag.getParameters()[0]); assertEquals(2, tag.getParameters().length); assertEquals("ed", tag.getParameters()[1]); } public void testJiraQdox45() { DocletTag tag = createDocletTag("key", "param = \"value\""); assertEquals("value", tag.getNamedParameter("param")); } public void testJiraQdox50() { DocletTag tag = createDocletTag("key", "param=\" value\""); assertEquals(" value", tag.getNamedParameter("param")); } } qdox-qdox-1.12.1/src/test/com/thoughtworks/qdox/model/AbstractJavaEntityTest.java000066400000000000000000000162241204551233600301420ustar00rootroot00000000000000package com.thoughtworks.qdox.model; import junit.framework.TestCase; import java.util.List; import java.util.LinkedList; public class AbstractJavaEntityTest extends TestCase { public AbstractJavaEntityTest(String s) { super(s); } public void testGetTagsByNameMethod() throws Exception { AbstractJavaEntity entity = new JavaField(); List tags = new LinkedList(); tags.add(new DefaultDocletTag("monkey", "is good")); tags.add(new DefaultDocletTag("monkey", "is funny")); tags.add(new DefaultDocletTag("horse", "not so much")); entity.setTags(tags); assertEquals(2, entity.getTagsByName("monkey").length); assertEquals(1, entity.getTagsByName("horse").length); assertEquals(0, entity.getTagsByName("non existent tag").length); } public void testGetSingleTagByName() throws Exception { AbstractJavaEntity entity = new JavaField(); List tags = new LinkedList(); tags.add(new DefaultDocletTag("monkey", "is good")); tags.add(new DefaultDocletTag("monkey", "is funny")); tags.add(new DefaultDocletTag("horse", "not so much")); entity.setTags(tags); assertEquals("is good", entity.getTagByName("monkey").getValue()); assertEquals("not so much", entity.getTagByName("horse").getValue()); assertNull(entity.getTagByName("cow")); } public void testCommentToString() { // setup AbstractJavaEntity entity = new JavaField(); IndentBuffer buffer = new IndentBuffer(); entity.setComment("Hello"); // expectation String expected = "" + "/**\n" + " * Hello\n" + " */\n"; // run entity.commentHeader(buffer); // verify assertEquals(expected, buffer.toString()); } public void testMultilineCommentToString() { AbstractJavaEntity entity = new JavaField(); IndentBuffer buffer = new IndentBuffer(); entity.setComment("Hello\nWorld"); // expectation String expected = "" + "/**\n" + " * Hello\n" + " * World\n" + " */\n"; // run entity.commentHeader(buffer); // verify assertEquals(expected, buffer.toString()); } public void testNoCommentToString() { // setup AbstractJavaEntity entity = new JavaField(); IndentBuffer buffer = new IndentBuffer(); // expectation String expected = ""; // run entity.commentHeader(buffer); // verify assertEquals(expected, buffer.toString()); } public void testCommentWithTagToString() { // setup AbstractJavaEntity entity = new JavaField(); IndentBuffer buffer = new IndentBuffer(); entity.setComment("Hello"); List tags = new LinkedList(); tags.add(new DefaultDocletTag("monkey", "is in the tree")); entity.setTags(tags); // expectation String expected = "" + "/**\n" + " * Hello\n" + " *\n" + " * @monkey is in the tree\n" + " */\n"; // run entity.commentHeader(buffer); // verify assertEquals(expected, buffer.toString()); } public void testCommentWithMultipleTagsToString() { // setup AbstractJavaEntity entity = new JavaField(); IndentBuffer buffer = new IndentBuffer(); entity.setComment("Hello"); List tags = new LinkedList(); tags.add(new DefaultDocletTag("monkey", "is in the tree")); tags.add(new DefaultDocletTag("see", "the doctor")); entity.setTags(tags); // expectation String expected = "" + "/**\n" + " * Hello\n" + " *\n" + " * @monkey is in the tree\n" + " * @see the doctor\n" + " */\n"; // run entity.commentHeader(buffer); // verify assertEquals(expected, buffer.toString()); } public void testTagButNoCommentToString() { // setup AbstractJavaEntity entity = new JavaField(); IndentBuffer buffer = new IndentBuffer(); List tags = new LinkedList(); tags.add(new DefaultDocletTag("monkey", "is in the tree")); entity.setTags(tags); // expectation String expected = "" + "/**\n" + " * @monkey is in the tree\n" + " */\n"; // run entity.commentHeader(buffer); // verify assertEquals(expected, buffer.toString()); } public void testTagWithNoValueToString() { // setup AbstractJavaEntity entity = new JavaField(); IndentBuffer buffer = new IndentBuffer(); List tags = new LinkedList(); tags.add(new DefaultDocletTag("monkey", "")); entity.setTags(tags); // expectation String expected = "" + "/**\n" + " * @monkey\n" + " */\n"; // run entity.commentHeader(buffer); // verify assertEquals(expected, buffer.toString()); } public void testPublicModifer() { AbstractJavaEntity entity = new JavaField(); entity.setModifiers(new String[]{"public"}); assertTrue(entity.isPublic()); } public void testPrivateModifer() { AbstractJavaEntity entity = new JavaField(); entity.setModifiers(new String[]{"private"}); assertTrue(entity.isPrivate()); } public void testAbstractModifer() { AbstractJavaEntity entity = new JavaField(); entity.setModifiers(new String[]{"public", "abstract"}); assertTrue(entity.isAbstract()); assertTrue(!entity.isPrivate()); } public void testProtectedModifer() { AbstractJavaEntity entity = new JavaField(); entity.setModifiers(new String[]{"protected", "abstract", "synchronized", "transient"}); assertTrue(entity.isProtected()); assertTrue(entity.isSynchronized()); assertTrue(entity.isTransient()); } public void testStaticModifer() { AbstractJavaEntity entity = new JavaField(); entity.setModifiers(new String[]{"public", "static", "final"}); assertTrue(entity.isStatic()); assertTrue(entity.isFinal()); } public void testQDOX30() { AbstractJavaEntity entity = new JavaField(); entity.setModifiers(new String[]{"native", "volatile", "strictfp"}); assertTrue(entity.isNative()); assertTrue(entity.isVolatile()); assertTrue(entity.isStrictfp()); } public void testGetTagsReturnsEmptyArrayInsteadOfNull() throws Exception { AbstractJavaEntity entity = new JavaField(); assertEquals(0, entity.getTags().length); } public void testGetSource() { JavaSource source = new JavaSource(); JavaClass clazz = new JavaClass(); source.addClass(clazz); JavaField field = new JavaField(); clazz.addField(field); assertEquals(source, field.getSource()); } } qdox-qdox-1.12.1/src/test/com/thoughtworks/qdox/model/ClassLibraryTest.java000066400000000000000000000041571204551233600267740ustar00rootroot00000000000000package com.thoughtworks.qdox.model; import junit.framework.TestCase; import java.util.Collection; public class ClassLibraryTest extends TestCase { public ClassLibraryTest(String s) { super(s); } public JavaClass getClassByName(String name) { JavaClass clazz = new JavaClass(); clazz.setName("MyClass"); return clazz; } public JavaClass[] getClasses() { return new JavaClass[0]; } public void testAdd() throws Exception { ClassLibrary c = new ClassLibrary(); c.add("com.blah.Ping"); c.add("com.moo.Poo"); assertTrue(c.contains("com.blah.Ping")); assertTrue(c.contains("com.moo.Poo")); assertTrue(!c.contains("com.not.You")); } public void testListAll() throws Exception { ClassLibrary c = new ClassLibrary(); c.add("com.blah.Ping"); c.add("com.thing.Ping"); c.add("com.x.Goat"); c.add("com.y.Goat"); Collection all = c.all(); assertTrue(all.contains("com.blah.Ping")); assertTrue(all.contains("com.thing.Ping")); assertTrue(all.contains("com.x.Goat")); assertTrue(all.contains("com.y.Goat")); assertTrue(!all.contains("com.not.True")); assertEquals(4, all.size()); } public void testNoClassLoaders() throws Exception { ClassLibrary c = new ClassLibrary(); assertTrue(!c.contains("java.lang.String")); } public void testWithClassLoader() throws Exception { ClassLibrary c = new ClassLibrary(); c.addClassLoader(getClass().getClassLoader()); assertTrue(c.contains("java.lang.String")); assertTrue(c.contains("java.util.Collection")); assertTrue(!c.contains("java.util.GoatCrusher")); } public void testDefaultClassLoader() throws Exception { ClassLibrary c = new ClassLibrary(); c.addDefaultLoader(); assertTrue(c.contains("java.lang.String")); assertTrue(c.contains("java.util.Collection")); assertTrue(c.contains("java.util.Map$Entry")); assertTrue(!c.contains("java.util.GoatCrusher")); } } qdox-qdox-1.12.1/src/test/com/thoughtworks/qdox/model/DefaultDocletTagTest.java000066400000000000000000000016011204551233600275440ustar00rootroot00000000000000package com.thoughtworks.qdox.model; import com.thoughtworks.qdox.model.util.SerializationUtils; import java.util.Map; /** * * @author Aslak Hellesøy * @version $Revision$ */ public class DefaultDocletTagTest extends AbstractDocletTagTest { public DefaultDocletTagTest(String name) { super(name); } private final DocletTagFactory docletTagFactory = new DefaultDocletTagFactory(); protected DocletTagFactory getDocletTagFactory() { return docletTagFactory; } public void testJiraQdox60() throws Exception { DefaultDocletTag tag = new DefaultDocletTag("author", "Excalibur Development Team"); tag = (DefaultDocletTag) SerializationUtils.serializedCopy(tag); Map paramMap = tag.getNamedParameterMap(); assertEquals(0, paramMap.size()); } } qdox-qdox-1.12.1/src/test/com/thoughtworks/qdox/model/IndentBufferTest.java000066400000000000000000000023731204551233600267530ustar00rootroot00000000000000package com.thoughtworks.qdox.model; import junit.framework.TestCase; public class IndentBufferTest extends TestCase { private IndentBuffer buffer; public IndentBufferTest(String s) { super(s); } protected void setUp() throws Exception { super.setUp(); buffer = new IndentBuffer(); } public void testNoIndentation() throws Exception { buffer.write("A string"); buffer.newline(); buffer.write("more string"); buffer.write('s'); buffer.newline(); String expected = "" + "A string\n" + "more strings\n"; assertEquals(expected, buffer.toString()); } public void testIndentation() throws Exception { buffer.write("Line1"); buffer.newline(); buffer.indent(); buffer.write("Indent1"); buffer.newline(); buffer.write("Indent2"); buffer.write(" more"); buffer.newline(); buffer.deindent(); buffer.write("Line2"); buffer.newline(); String expected = "" + "Line1\n" + "\tIndent1\n" + "\tIndent2 more\n" + "Line2\n"; assertEquals(expected, buffer.toString()); } } qdox-qdox-1.12.1/src/test/com/thoughtworks/qdox/model/JavaClassTest.java000066400000000000000000000537201204551233600262510ustar00rootroot00000000000000package com.thoughtworks.qdox.model; import junit.framework.TestCase; import java.util.HashMap; public class JavaClassTest extends TestCase { private JavaClass cls; private JavaSource src; public JavaClassTest(String s) { super(s); } protected void setUp() throws Exception { super.setUp(); src = new JavaSource(); cls = new JavaClass(); src.addClass(cls); } public void testGetCodeBlockSimpleClass() throws Exception { cls.setName("MyClass"); String expected = "" + "class MyClass {\n" + "\n" + "}\n"; assertEquals(expected, cls.getCodeBlock()); } public void testGetCodeBlockSimpleInterface() throws Exception { cls.setName("MyClass"); cls.setInterface(true); String expected = "" + "interface MyClass {\n" + "\n" + "}\n"; assertEquals(expected, cls.getCodeBlock()); } public void testGetCodeBlockSimpleEnum() throws Exception { cls.setName("MyEnum"); cls.setEnum(true); String expected = "" + "enum MyEnum {\n" + "\n" + "}\n"; assertEquals(expected, cls.getCodeBlock()); } public void testGetCodeBlockClassExtends() throws Exception { cls.setName("MyClass"); cls.setSuperClass(new Type("SuperClass")); String expected = "" + "class MyClass extends SuperClass {\n" + "\n" + "}\n"; assertEquals(expected, cls.getCodeBlock()); } public void testGetCodeBlockInterfaceExtends() throws Exception { cls.setName("MyClass"); cls.setImplementz(type(new String[]{"SomeInterface"})); cls.setInterface(true); String expected = "" + "interface MyClass extends SomeInterface {\n" + "\n" + "}\n"; assertEquals(expected, cls.getCodeBlock()); } public void testGetCodeBlockInterfaceExtendsTwo() throws Exception { cls.setName("MyClass"); cls.setImplementz(type(new String[]{"SomeInterface", "AnotherInterface"})); cls.setInterface(true); String expected = "" + "interface MyClass extends SomeInterface, AnotherInterface {\n" + "\n" + "}\n"; assertEquals(expected, cls.getCodeBlock()); } public void testGetCodeBlockInterfaceExtendsThree() throws Exception { cls.setName("MyClass"); cls.setImplementz(type(new String[]{"SomeInterface", "AnotherInterface", "Thingy"})); cls.setInterface(true); String expected = "" + "interface MyClass extends SomeInterface, AnotherInterface, Thingy {\n" + "\n" + "}\n"; assertEquals(expected, cls.getCodeBlock()); } public void testGetCodeBlockClassImplements() throws Exception { cls.setName("MyClass"); cls.setImplementz(type(new String[]{"SomeInterface"})); String expected = "" + "class MyClass implements SomeInterface {\n" + "\n" + "}\n"; assertEquals(expected, cls.getCodeBlock()); } public void testGetCodeBlockClassImplementsTwo() throws Exception { cls.setName("MyClass"); cls.setImplementz(type(new String[]{"SomeInterface", "AnotherInterface", "Xx"})); String expected = "" + "class MyClass implements SomeInterface, AnotherInterface, Xx {\n" + "\n" + "}\n"; assertEquals(expected, cls.getCodeBlock()); } public void testGetCodeBlockClassImplementsAndExtends() throws Exception { cls.setName("MyClass"); cls.setImplementz(type(new String[]{"SomeInterface", "AnotherInterface", "Xx"})); cls.setSuperClass(new Type("SubMarine")); String expected = "" + "class MyClass extends SubMarine implements SomeInterface, AnotherInterface, Xx {\n" + "\n" + "}\n"; assertEquals(expected, cls.getCodeBlock()); } public void testGetCodeBlockModifers() throws Exception { cls.setName("MyClass"); cls.setModifiers(new String[]{"public", "final"}); String expected = "" + "public final class MyClass {\n" + "\n" + "}\n"; assertEquals(expected, cls.getCodeBlock()); } public void testGetCodeBlockModifersProtectionAlwaysFirst() throws Exception { cls.setName("MyClass"); cls.setModifiers(new String[]{"final", "public"}); String expected = "" + "public final class MyClass {\n" + "\n" + "}\n"; assertEquals(expected, cls.getCodeBlock()); cls.setModifiers(new String[]{"abstract", "protected"}); expected = "" + "protected abstract class MyClass {\n" + "\n" + "}\n"; assertEquals(expected, cls.getCodeBlock()); } public void testGetCodeBlockClassWithOneMethod() throws Exception { cls.setName("MyClass"); JavaMethod mth = new JavaMethod(); mth.setName("doStuff"); mth.setReturns(new Type("void")); cls.addMethod(mth); String expected = "" + "class MyClass {\n" + "\n" + "\tvoid doStuff();\n" + "\n" + "}\n"; assertEquals(expected, cls.getCodeBlock()); } public void testGetCodeBlockClassWithThreeMethods() throws Exception { cls.setName("MyClass"); { JavaMethod mth = new JavaMethod(); mth.setName("doStuff"); mth.setReturns(new Type("void")); cls.addMethod(mth); } { JavaMethod mth = new JavaMethod(); mth.setName("somethingElse"); mth.setReturns(new Type("Goose")); cls.addMethod(mth); } { JavaMethod mth = new JavaMethod(); mth.setName("eat"); mth.setReturns(new Type("void")); cls.addMethod(mth); } String expected = "" + "class MyClass {\n" + "\n" + "\tvoid doStuff();\n" + "\n" + "\tGoose somethingElse();\n" + "\n" + "\tvoid eat();\n" + "\n" + "}\n"; assertEquals(expected, cls.getCodeBlock()); } public void testGetCodeBlockClassWithTwoFields() throws Exception { cls.setName("MyClass"); { JavaField fld = new JavaField(); fld.setName("count"); fld.setType(new Type("int")); cls.addField(fld); } { JavaField fld = new JavaField(); fld.setName("thing"); fld.setType(new Type("String")); fld.setModifiers(new String[]{"public"}); cls.addField(fld); } String expected = "" + "class MyClass {\n" + "\n" + "\tint count;\n" + "\n" + "\tpublic String thing;\n" + "\n" + "}\n"; assertEquals(expected, cls.getCodeBlock()); } public void testGetCodeBlockClassWithInnerClass() throws Exception { cls.setName("Outer"); JavaClass innerClass = new JavaClass(); innerClass.setName("Inner"); cls.addClass(innerClass); String expected = "" + "class Outer {\n" + "\n" + "\tclass Inner {\n" + "\n" + "\t}\n" + "\n" + "}\n"; assertEquals(expected, cls.getCodeBlock()); } public void testGetCodeBlockClassWithInnerEnum() throws Exception { cls.setName("Outer"); JavaClass innerEnum = new JavaClass(); innerEnum.setEnum(true); innerEnum.setName("Inner"); cls.addClass(innerEnum); String expected = "" + "class Outer {\n" + "\n" + "\tenum Inner {\n" + "\n" + "\t}\n" + "\n" + "}\n"; assertEquals(expected, cls.getCodeBlock()); } public void testGetCodeBlockEnumWithInnerClass() throws Exception { cls.setName("Outer"); cls.setEnum(true); JavaClass innerClass = new JavaClass(); innerClass.setName("Inner"); cls.addClass(innerClass); String expected = "" + "enum Outer {\n" + "\n" + "\tclass Inner {\n" + "\n" + "\t}\n" + "\n" + "}\n"; assertEquals(expected, cls.getCodeBlock()); } public void testGetCodeBlockClassWithComment() throws Exception { cls.setName("MyClass"); cls.setComment("Hello World"); String expected = "" + "/**\n" + " * Hello World\n" + " */\n" + "class MyClass {\n" + "\n" + "}\n"; assertEquals(expected, cls.getCodeBlock()); } public void testGetCodeBlockClassWithIndentedCommentsForFieldAndMethod() throws Exception { cls.setName("MyClass"); cls.setComment("Hello World"); JavaMethod mth = new JavaMethod(); mth.setReturns(new Type("String")); mth.setName("thingy"); mth.setComment("Hello Method"); cls.addMethod(mth); JavaField fld = new JavaField(); fld.setType(new Type("String")); fld.setName("thing"); fld.setComment("Hello Field"); cls.addField(fld); String expected = "" + "/**\n" + " * Hello World\n" + " */\n" + "class MyClass {\n" + "\n" + "\t/**\n" + "\t * Hello Field\n" + "\t */\n" + "\tString thing;\n" + "\n" + "\t/**\n" + "\t * Hello Method\n" + "\t */\n" + "\tString thingy();\n" + "\n" + "}\n"; assertEquals(expected, cls.getCodeBlock()); } public void testIsPublic() { cls.setName("MyClass"); assertTrue(!cls.isPublic()); cls.setModifiers(new String[]{"public"}); assertTrue(cls.isPublic()); } public void testQualifiedType() throws Exception { src.setPackage(new JavaPackage("com.thoughtworks.qdox", new HashMap())); cls.setName("MyClass"); assertEquals("MyClass", cls.getName()); assertEquals("com.thoughtworks.qdox", cls.getPackage().getName()); assertEquals("com.thoughtworks.qdox", cls.getPackageName()); assertEquals("com.thoughtworks.qdox.MyClass", cls.getFullyQualifiedName()); assertTrue(cls.asType().isResolved()); assertEquals("com.thoughtworks.qdox.MyClass", cls.asType().getValue()); } public void testGetClassNamePrefix() { src.setPackage(new JavaPackage("foo.bar", new HashMap())); cls.setName("Stanley"); assertEquals("foo.bar.Stanley$", cls.getClassNamePrefix()); } public void testInnerClass() throws Exception { src.setPackage(new JavaPackage("foo.bar", new HashMap())); JavaClass outer = new JavaClass(); outer.setName("Outer"); src.addClass(outer); JavaClass inner = new JavaClass(); inner.setName("Inner"); outer.addClass(inner); assertEquals("Inner", inner.getName()); assertEquals("foo.bar", inner.getPackage().getName()); assertEquals("foo.bar", inner.getPackageName()); assertEquals("foo.bar.Outer$Inner", inner.getFullyQualifiedName()); } public void testDefaultPackageClass() { src.setPackage(null); cls.setName("DefaultPackageClass"); assertEquals("", src.getClasses()[0].getPackageName()); assertEquals("DefaultPackageClass", src.getClasses()[0].getFullyQualifiedName()); } public void testDefaultClassSuperclass() throws Exception { cls.setName("MyClass"); assertEquals("java.lang.Object", cls.getSuperClass().getValue()); cls.setSuperClass(new Type("x.X")); assertEquals("x.X", cls.getSuperClass().getValue()); } public void testDefaultInterfaceSuperclass() throws Exception { cls.setName("MyInterface"); cls.setInterface(true); assertNull(cls.getSuperClass()); cls.setSuperClass(new Type("x.X")); assertEquals("x.X", cls.getSuperClass().getValue()); } public void testEnumSuperclass() throws Exception { cls.setName("MyEnum"); cls.setEnum(true); assertEquals("java.lang.Enum", cls.getSuperClass().getValue()); } public void testEnumCannotExtendAnythingElse() throws Exception { cls.setName("MyEnum"); cls.setEnum(true); try { cls.setSuperClass(new Type("x.X")); fail("expected an exception"); } catch (IllegalArgumentException e) { assertEquals("enums cannot extend other classes", e.getMessage()); } } public void testCanGetFieldByName() throws Exception { JavaField fredField = new JavaField(); fredField.setName("fred"); fredField.setType(new Type("int")); cls.addField(fredField); assertEquals(fredField, cls.getFieldByName("fred")); assertEquals(null, cls.getFieldByName("barney")); } public void testCanGetMethodBySignature() { JavaMethod method = new JavaMethod(); method.setReturns(new Type("void")); method.setName("doStuff"); method.addParameter( new JavaParameter(new Type("int"), "x") ); method.addParameter( new JavaParameter(new Type("double"), "y") ); cls.addMethod(method); Type[] correctTypes = type(new String[]{"int", "double"}); assertSame( method, cls.getMethodBySignature("doStuff", correctTypes) ); assertEquals( null, cls.getMethodBySignature("doStuff", new Type[0]) ); assertEquals( null, cls.getMethodBySignature("sitIdlyBy", correctTypes) ); } public void testCanGetInnerClassByName() throws Exception { JavaClass innerClass = new JavaClass(); innerClass.setName("Inner"); cls.addClass(innerClass); assertEquals(innerClass, cls.getNestedClassByName("Inner")); assertEquals(null, cls.getNestedClassByName("Bogus")); } public void testResolveTypeDefaultsToParentScope() throws Exception { cls.setName("X"); assertEquals("int", cls.resolveType("int")); } public void testResolveTypeInnerClass() throws Exception { src.setPackage(new JavaPackage("p", new HashMap())); cls.setName("X"); JavaClass innerClass = new JavaClass(); innerClass.setName("DogFood"); cls.addClass(innerClass); assertEquals("p.X$DogFood", cls.resolveType("DogFood")); assertEquals(null, cls.resolveType("Food")); } public void testGetBeanPropertiesReturnsEmptyForEmptyClass() throws Exception { assertEquals(0, cls.getBeanProperties().length); } public void testGetBeanPropertiesFindsSimpleProperties() throws Exception { JavaMethod setFooMethod = new JavaMethod("setFoo"); setFooMethod.addParameter(new JavaParameter(new Type("int"), "foo")); cls.addMethod(setFooMethod); JavaMethod getFooMethod = new JavaMethod(new Type("int"), "getFoo"); cls.addMethod(getFooMethod); assertEquals(1, cls.getBeanProperties().length); BeanProperty fooProp = cls.getBeanProperties()[0]; assertEquals("foo", fooProp.getName()); assertEquals(new Type("int"), fooProp.getType()); assertEquals(getFooMethod, fooProp.getAccessor()); assertEquals(setFooMethod, fooProp.getMutator()); } public void testToStringClass() { cls.setName("com.MyClass"); assertEquals("class com.MyClass", cls.toString()); } public void testInnerClassToString() throws Exception { JavaPackage jPackage = new JavaPackage("com.thoughtworks.qdox.model"); JavaClass jOuterClass = new JavaClass("OuterClass"); jPackage.addClass(jOuterClass); JavaClass jInnerClass = new JavaClass("InnerClass"); jOuterClass.addClass(jInnerClass); assertEquals("class com.thoughtworks.qdox.model.OuterClass$InnerClass", jInnerClass.toString()); } public void testInnerClassType() { JavaPackage jPackage = new JavaPackage("com.thoughtworks.qdox.model"); JavaClass jOuterClass = new JavaClass("OuterClass"); jPackage.addClass(jOuterClass); JavaClass jInnerClass = new JavaClass("InnerClass"); jOuterClass.addClass(jInnerClass); assertEquals("com.thoughtworks.qdox.model.OuterClass.InnerClass", jInnerClass.asType().getValue()); } public void testInnerInterfaceToString() { JavaPackage jPackage = new JavaPackage("com.thoughtworks.qdox.model"); JavaClass jOuterClass = new JavaClass("OuterClass"); jPackage.addClass(jOuterClass); JavaClass jInnerInterface = new JavaClass("InnerInterface"); jInnerInterface.setInterface(true); jOuterClass.addClass(jInnerInterface); assertEquals("interface com.thoughtworks.qdox.model.OuterClass$InnerInterface", jInnerInterface.toString()); } public void testToStringInterface() { cls.setName("com.MyClass"); cls.setInterface(true); assertEquals("interface com.MyClass", cls.toString()); } public void testToStringVoid() { cls.setName("com.MyClass"); cls.addMethod(new JavaMethod(Type.VOID, "doSomething")); JavaMethod javaMethod = cls.getMethods()[0]; assertEquals("void", javaMethod.getReturns().toString()); } public void testToStringBoolean() { cls.setName("com.MyClass"); cls.addMethod(new JavaMethod(new Type("boolean"), "doSomething")); JavaMethod javaMethod = cls.getMethods()[0]; assertEquals("boolean", javaMethod.getReturns().toString()); } public void testToStringInt() { cls.setName("com.MyClass"); cls.addMethod(new JavaMethod(new Type("int"), "doSomething")); JavaMethod javaMethod = cls.getMethods()[0]; assertEquals("int", javaMethod.getReturns().toString()); } public void testToStringLong() { cls.setName("com.MyClass"); cls.addMethod(new JavaMethod(new Type("long"), "doSomething")); JavaMethod javaMethod = cls.getMethods()[0]; assertEquals("long", javaMethod.getReturns().toString()); } public void testToStringFloat() { cls.setName("com.MyClass"); cls.addMethod(new JavaMethod(new Type("float"), "doSomething")); JavaMethod javaMethod = cls.getMethods()[0]; assertEquals("float", javaMethod.getReturns().toString()); } public void testToStringDouble() { cls.setName("com.MyClass"); cls.addMethod(new JavaMethod(new Type("double"), "doSomething")); JavaMethod javaMethod = cls.getMethods()[0]; assertEquals("double", javaMethod.getReturns().toString()); } public void testToStringChar() { cls.setName("com.MyClass"); cls.addMethod(new JavaMethod(new Type("char"), "doSomething")); JavaMethod javaMethod = cls.getMethods()[0]; assertEquals("char", javaMethod.getReturns().toString()); } public void testToStringByte() { cls.setName("com.MyClass"); cls.addMethod(new JavaMethod(new Type("byte"), "doSomething")); JavaMethod javaMethod = cls.getMethods()[0]; assertEquals("byte", javaMethod.getReturns().toString()); } /** * @codehaus.jira QDOX-59 */ public void testBeanPropertiesAreReturnedInOrderDeclared() { cls.addMethod(new JavaMethod(new Type("int"), "getFoo")); cls.addMethod(new JavaMethod(new Type("int"), "getBar")); cls.addMethod(new JavaMethod(new Type("String"), "getMcFnord")); BeanProperty[] properties = cls.getBeanProperties(); assertEquals(3, properties.length); assertEquals("foo", properties[0].getName()); assertEquals("bar", properties[1].getName()); assertEquals("mcFnord", properties[2].getName()); } private Type[] type(String[] typeNames) { Type[] result = new Type[typeNames.length]; for (int i = 0; i < typeNames.length; i++) { result[i] = new Type(typeNames[i]); } return result; } // QDOX-201 public void testGetVarArgMethodSignature() { JavaMethod simpleMethod = new JavaMethod( "doSomething" ); simpleMethod.addParameter( new JavaParameter( new Type("String"), "param", false ) ); JavaMethod varArgMethod = new JavaMethod( "doSomething" ); varArgMethod.addParameter( new JavaParameter( new Type("String"), "param", true ) ); cls.addMethod( simpleMethod ); cls.addMethod( varArgMethod ); assertEquals( simpleMethod, cls.getMethodBySignature( "doSomething", new Type[] {new Type("String")} ) ); assertEquals( simpleMethod, cls.getMethodBySignature( "doSomething", new Type[] {new Type("String")}, false ) ); assertEquals( simpleMethod, cls.getMethodBySignature( "doSomething", new Type[] {new Type("String")}, true ) ); assertEquals( simpleMethod, cls.getMethodBySignature( "doSomething", new Type[] {new Type("String")}, false, false ) ); assertEquals( varArgMethod, cls.getMethodBySignature( "doSomething", new Type[] {new Type("String")}, false, true ) ); assertEquals( simpleMethod, cls.getMethodBySignature( "doSomething", new Type[] {new Type("String")}, true, false ) ); assertEquals( varArgMethod, cls.getMethodBySignature( "doSomething", new Type[] {new Type("String")}, true, true ) ); } } qdox-qdox-1.12.1/src/test/com/thoughtworks/qdox/model/JavaFieldTest.java000066400000000000000000000074271204551233600262320ustar00rootroot00000000000000package com.thoughtworks.qdox.model; import junit.framework.TestCase; public class JavaFieldTest extends TestCase { public JavaFieldTest(String s) { super(s); } public void testGetCodeBlock() throws Exception { JavaField fld = new JavaField(); fld.setName("count"); fld.setType(new Type("int")); assertEquals("int count;\n", fld.getCodeBlock()); } public void testGetCodeBlockWithModifiers() throws Exception { JavaField fld = new JavaField(); fld.setName("count"); fld.setType(new Type("int")); fld.setModifiers(new String[]{"public", "final"}); assertEquals("public final int count;\n", fld.getCodeBlock()); } public void testGetCodeBlockWithComment() throws Exception { JavaField fld = new JavaField(); fld.setName("count"); fld.setType(new Type("int")); fld.setComment("Hello"); String expected = "" + "/**\n" + " * Hello\n" + " */\n" + "int count;\n"; assertEquals(expected, fld.getCodeBlock()); } public void testGetCodeBlock1dArray() throws Exception { JavaField fld = new JavaField(); fld.setName("count"); fld.setType(new Type("int", 1)); String expected = "int[] count;\n"; assertEquals(expected, fld.getCodeBlock()); } public void testGetCodeBlock2dArray() throws Exception { JavaField fld = new JavaField(); fld.setName("count"); fld.setType(new Type("int", 2)); String expected = "int[][] count;\n"; assertEquals(expected, fld.getCodeBlock()); } public void testGetCodeBlockWithValue() throws Exception { JavaField fld = new JavaField(); fld.setName("stuff"); fld.setType(new Type("String")); fld.setInitializationExpression("STUFF + getThing()"); String expected = "String stuff = STUFF + getThing();\n"; assertEquals(expected, fld.getCodeBlock()); } public void testShouldReturnFieldNameForCallSignature() throws Exception { JavaField fld = new JavaField(); fld.setName("count"); fld.setType(new Type("int")); fld.setModifiers(new String[]{"public", "final"}); assertEquals("count", fld.getCallSignature()); } public void testShouldReturnProperDeclarationSignatureWithModifiers() throws Exception { JavaField fld = new JavaField(); fld.setName("count"); fld.setType(new Type("int")); fld.setModifiers(new String[]{"public", "final"}); assertEquals("public final int count", fld.getDeclarationSignature(true)); } public void testShouldReturnProperDeclarationSignatureWithoutModifiers() throws Exception { JavaField fld = new JavaField(); fld.setName("count"); fld.setType(new Type("int")); fld.setModifiers(new String[]{"public", "final"}); assertEquals("int count", fld.getDeclarationSignature(false)); } public void testToStringThreadMIN_PRIORITY() throws Exception { JavaClass cls = new JavaClass("java.lang.Thread"); JavaField fld = new JavaField(new Type("int"), "MIN_PRIORITY"); fld.setModifiers(new String[] {"final", "static", "public"}); cls.addField(fld); assertEquals("public static final int java.lang.Thread.MIN_PRIORITY", fld.toString()); } public void testToStringFieldDescriptorFd() throws Exception { JavaPackage pckg = new JavaPackage("java.io"); JavaClass cls = new JavaClass("FileDescriptor"); pckg.addClass(cls); JavaField fld = new JavaField(new Type("int"), "fd"); fld.setModifiers(new String[]{"private"}); cls.addField(fld); assertEquals("private int java.io.FileDescriptor.fd", fld.toString()); } } qdox-qdox-1.12.1/src/test/com/thoughtworks/qdox/model/JavaMethodTest.java000066400000000000000000000357321204551233600264270ustar00rootroot00000000000000package com.thoughtworks.qdox.model; import junit.framework.TestCase; public class JavaMethodTest extends TestCase { private JavaMethod mth; private JavaSource source; private JavaClass clazz; public JavaMethodTest(String s) { super(s); } protected void setUp() throws Exception { super.setUp(); source = new JavaSource(); clazz = new JavaClass(); source.addClass(clazz); mth = new JavaMethod(); clazz.addMethod(mth); } public void testDeclarationSignatureWithModifiers() { createSignatureTestMethod(); String signature = mth.getDeclarationSignature(true); assertEquals("protected final void blah(int count, MyThing t) throws FishException, FruitException", signature); } public void testDeclarationSignatureWithoutModifiers() { createSignatureTestMethod(); String signature = mth.getDeclarationSignature(false); assertEquals("void blah(int count, MyThing t) throws FishException, FruitException", signature); } public void testCallSignature() { createSignatureTestMethod(); String signature = mth.getCallSignature(); assertEquals("blah(count, t)", signature); } private void createSignatureTestMethod() { mth.setName("blah"); mth.setModifiers(new String[]{"protected", "final"}); mth.setReturns(new Type("void")); mth.setExceptions(new Type[] { new Type("FishException"), new Type("FruitException"), }); mth.addParameter(new JavaParameter(new Type("int"), "count")); mth.addParameter(new JavaParameter(new Type("MyThing"), "t")); } // public void testSignatureWithVarArgs() throws Exception { // mth.setName( "method" ); // mth.addParameter( new JavaParameter(new Type("java.lang.String"), "param", true) ); // assertEquals( mth, clazz.getMethodBySignature( "method", new Type[] { new Type("java.lang.String", true)} ) ); // } public void testGetCodeBlockSimple() throws Exception { mth.setName("doSomething"); mth.setReturns(new Type("java.lang.String")); assertEquals("java.lang.String doSomething();\n", mth.getCodeBlock()); } public void testGetCodeBlockOneParam() throws Exception { mth.setName("blah"); mth.setReturns(new Type("void")); mth.addParameter(new JavaParameter(new Type("String"), "thingy")); assertEquals("void blah(String thingy);\n", mth.getCodeBlock()); } public void testGetCodeBlockTwoParams() throws Exception { mth.setName("blah"); mth.setReturns(new Type("void")); mth.addParameter(new JavaParameter(new Type("int"), "count")); mth.addParameter(new JavaParameter(new Type("MyThing"), "t")); assertEquals("void blah(int count, MyThing t);\n", mth.getCodeBlock()); } public void testGetCodeBlockThreeParams() throws Exception { mth.setName("blah"); mth.setReturns(new Type("void")); mth.addParameter(new JavaParameter(new Type("int"), "count")); mth.addParameter(new JavaParameter(new Type("MyThing"), "t")); mth.addParameter(new JavaParameter(new Type("java.lang.Meat"), "beef")); assertEquals("void blah(int count, MyThing t, java.lang.Meat beef);\n", mth.getCodeBlock()); } public void testGetCodeBlockModifiersWithAccessLevelFirst() throws Exception { mth.setName("blah"); mth.setReturns(new Type("void")); mth.setModifiers(new String[]{"synchronized", "public", "final"}); assertEquals("public synchronized final void blah();\n", mth.getCodeBlock()); } public void testGetCodeBlockOneException() throws Exception { mth.setName("blah"); mth.setReturns(new Type("void")); mth.setExceptions(new Type[]{new Type("RuntimeException")}); assertEquals("void blah() throws RuntimeException;\n", mth.getCodeBlock()); } public void testGetCodeBlockTwoException() throws Exception { mth.setName("blah"); mth.setReturns(new Type("void")); mth.setExceptions(new Type[]{new Type("RuntimeException"), new Type("java.lang.SheepException", 1)}); assertEquals("void blah() throws RuntimeException, java.lang.SheepException;\n", mth.getCodeBlock()); } public void testGetCodeBlockThreeException() throws Exception { mth.setName("blah"); mth.setReturns(new Type("void")); mth.setExceptions(new Type[]{new Type("RuntimeException"), new Type("java.lang.SheepException", 1), new Type("CowException", 1)}); assertEquals("void blah() throws RuntimeException, java.lang.SheepException, CowException;\n", mth.getCodeBlock()); } public void testGetCodeBlockConstructor() throws Exception { mth.setName("Blah"); mth.setModifiers(new String[]{"public"}); mth.setConstructor(true); assertEquals("public Blah();\n", mth.getCodeBlock()); } public void testGetCodeBlockWithComment() throws Exception { mth.setName("blah"); mth.setReturns(new Type("void")); mth.setComment("Hello"); String expect = "" + "/**\n" + " * Hello\n" + " */\n" + "void blah();\n"; assertEquals(expect, mth.getCodeBlock()); } public void testGetCodeBlock1dArray() throws Exception { mth.setName("doSomething"); mth.setReturns(new Type("java.lang.String", 1)); assertEquals("java.lang.String[] doSomething();\n", mth.getCodeBlock()); } public void testGetCodeBlock2dArray() throws Exception { mth.setName("doSomething"); mth.setReturns(new Type("java.lang.String", 2)); assertEquals("java.lang.String[][] doSomething();\n", mth.getCodeBlock()); } public void testGetCodeBlockParamArray() throws Exception { mth.setName("blah"); mth.setReturns(new Type("void")); mth.addParameter(new JavaParameter(new Type("int", 2), "count")); mth.addParameter(new JavaParameter(new Type("MyThing", 1), "t")); assertEquals("void blah(int[][] count, MyThing[] t);\n", mth.getCodeBlock()); } public void testGetCodeBlockWithBody() throws Exception { mth.setName("doStuff"); mth.setReturns(new Type("java.lang.String")); mth.setSourceCode(" int x = 2;\n return STUFF;\n"); assertEquals("" + "java.lang.String doStuff() {\n" + " int x = 2;\n" + " return STUFF;\n" + "}\n", mth.getCodeBlock()); } public void testEquals() throws Exception { mth.setName("thing"); mth.setReturns(new Type("void")); JavaMethod m2 = new JavaMethod(); m2.setName("thing"); m2.setReturns(new Type("void")); JavaMethod m3 = new JavaMethod(); m3.setName("thingy"); m3.setReturns(new Type("void")); JavaMethod m4 = new JavaMethod(); m4.setName("thing"); m4.setReturns(new Type("int")); JavaMethod m5 = new JavaMethod(); JavaMethod m6 = new JavaMethod(); JavaMethod m7 = new JavaMethod(); m7.setReturns( new Type("int") ); JavaMethod c1 = new JavaMethod(); c1.setName("thing"); c1.setConstructor(true); JavaMethod c2 = new JavaMethod(); c2.setName("Thong"); c2.setConstructor(true); JavaMethod c3 = new JavaMethod(); c3.setName("Thong"); c3.setConstructor(true); assertEquals(mth, m2); assertEquals(m2, mth); assertNotEquals(mth, m3); assertNotEquals(mth, m4); assertNotEquals(m4, c1); assertNotEquals(c1, c2); assertEquals(c2, c3); assertFalse(mth.equals(null)); assertNotEquals( m4, m5 ); assertNotEquals( m5, m4 ); assertEquals( m5, m6 ); assertNotEquals( m5, m7 ); } public void testEqualsWithParameters() throws Exception { mth.setName("thing"); mth.addParameter(new JavaParameter(new Type("int", 1), "blah")); mth.addParameter(new JavaParameter(new Type("java.lang.String", 2), "thing")); mth.addParameter(new JavaParameter(new Type("X", 3), "")); mth.setReturns(new Type("void")); JavaMethod m2 = new JavaMethod(); m2.setName("thing"); m2.addParameter(new JavaParameter(new Type("int", 1), "blah")); m2.addParameter(new JavaParameter(new Type("java.lang.String", 2), "anotherName")); m2.addParameter(new JavaParameter(new Type("X", 3), "blah")); m2.setReturns(new Type("void")); JavaMethod m3 = new JavaMethod(); m3.setName("thing"); m3.addParameter(new JavaParameter(new Type("int", 1), "blah")); m3.addParameter(new JavaParameter(new Type("java.lang.String", 2), "thing")); m3.setReturns(new Type("void")); JavaMethod m4 = new JavaMethod(); m4.setName("thing"); m4.addParameter(new JavaParameter(new Type("int", 1), "blah")); m4.addParameter(new JavaParameter(new Type("java.lang.String", 2), "thing")); m4.addParameter(new JavaParameter(new Type("TTTTTTTT", 3), "blah")); //name m4.setReturns(new Type("void")); JavaMethod m5 = new JavaMethod(); m5.setName("thing"); m5.addParameter(new JavaParameter(new Type("int", 1), "blah")); m5.addParameter(new JavaParameter(new Type("java.lang.String", 2), "thing")); m5.addParameter(new JavaParameter(new Type("X", 9), "blah")); // dimension m5.setReturns(new Type("void")); assertEquals(mth, m2); assertEquals(m2, mth); assertNotEquals(mth, m3); assertNotEquals(mth, m4); assertNotEquals(mth, m5); } public void testHashCode() throws Exception { mth.setName("thing"); mth.addParameter(new JavaParameter(new Type("int", 1), "blah")); mth.addParameter(new JavaParameter(new Type("java.lang.String", 2), "thing")); mth.addParameter(new JavaParameter(new Type("X", 3), "")); mth.setReturns(new Type("void")); JavaMethod m2 = new JavaMethod(); m2.setName("thing"); m2.addParameter(new JavaParameter(new Type("int", 1), "blah")); m2.addParameter(new JavaParameter(new Type("java.lang.String", 2), "anotherName")); m2.addParameter(new JavaParameter(new Type("X", 3), "blah")); m2.setReturns(new Type("void")); JavaMethod m3 = new JavaMethod(); m3.setName("thing"); m3.addParameter(new JavaParameter(new Type("int", 1), "blah")); m3.addParameter(new JavaParameter(new Type("java.lang.String", 2), "thing")); m3.setReturns(new Type("void")); JavaMethod c1 = new JavaMethod(); c1.setName("Thong"); c1.setConstructor(true); JavaMethod c2 = new JavaMethod(); c2.setName("Thong"); c2.setConstructor(true); assertEquals(mth.hashCode(), m2.hashCode()); assertTrue(mth.hashCode() != m3.hashCode()); assertEquals(c1.hashCode(), c2.hashCode()); } public void testSignatureMatches() throws Exception { mth.setName("thing"); mth.addParameter(new JavaParameter(new Type("int"), "x")); mth.addParameter(new JavaParameter(new Type("long", 2), "y")); mth.setReturns(new Type("void")); Type[] correctTypes = new Type[]{ new Type("int"), new Type("long", 2) }; Type[] wrongTypes1 = new Type[]{ new Type("int", 2), new Type("long") }; Type[] wrongTypes2 = new Type[]{ new Type("int"), new Type("long", 2), new Type("double") }; assertTrue(mth.signatureMatches("thing", correctTypes)); assertFalse(mth.signatureMatches("xxx", correctTypes)); assertFalse(mth.signatureMatches("thing", wrongTypes1)); assertFalse(mth.signatureMatches("thing", wrongTypes2)); } public void testVarArgSignatureMatches() throws Exception { mth.setName("thing"); mth.addParameter(new JavaParameter(new Type("int"), "x")); mth.addParameter(new JavaParameter(new Type("long", 2), "y", true)); mth.setReturns(new Type("void")); Type[] correctTypes = new Type[]{ new Type("int"), new Type("long", 2) }; Type[] wrongTypes1 = new Type[]{ new Type("int", 2), new Type("long") }; Type[] wrongTypes2 = new Type[]{ new Type("int"), new Type("long", 2), new Type("double") }; assertTrue(mth.signatureMatches("thing", correctTypes, true)); assertFalse(mth.signatureMatches("thing", correctTypes, false)); assertFalse(mth.signatureMatches("xxx", correctTypes, true)); assertFalse(mth.signatureMatches("thing", wrongTypes1, true)); assertFalse(mth.signatureMatches("thing", wrongTypes2, true)); } public void testParentClass() throws Exception { assertSame(clazz, mth.getParentClass()); } public void testCanGetParameterByName() throws Exception { JavaParameter paramX = new JavaParameter(new Type("int"), "x"); mth.addParameter(paramX); mth.addParameter(new JavaParameter(new Type("string"), "y")); assertEquals(paramX, mth.getParameterByName("x")); assertEquals(null, mth.getParameterByName("z")); } public void testToString() throws Exception { JavaClass cls = new JavaClass("java.lang.Object"); JavaMethod mthd = new JavaMethod(new Type("boolean"),"equals"); cls.addMethod(mthd); mthd.setModifiers(new String[]{"public"}); mthd.addParameter(new JavaParameter(new Type("java.lang.Object"), null)); assertEquals("public boolean java.lang.Object.equals(java.lang.Object)", mthd.toString()); } public void testConstructorToString() throws Exception { JavaClass cls = new JavaClass("a.b.Executor"); JavaMethod constructor = new JavaMethod(null,"Executor"); constructor.setConstructor( true ); cls.addMethod(constructor); assertEquals("a.b.Executor()", constructor.toString()); } public void testConstructorReturnType() throws Exception { JavaMethod constructor = new JavaMethod(null,"Executor"); constructor.setConstructor( true ); assertEquals(null, constructor.getReturnType()); } public void testConstructorParameterTypes() throws Exception { JavaClass cls = new JavaClass("a.b.Executor"); JavaMethod constructor = new JavaMethod(null,"Executor"); constructor.addParameter( new JavaParameter( new Type("a.b.C"), "param" ) ); constructor.setConstructor( true ); cls.addMethod(constructor); assertEquals("a.b.C", constructor.getParameterTypes()[0].toString()); } private void assertNotEquals(Object o1, Object o2) { assertTrue(o1.toString() + " should not equals " + o2.toString(), !o1.equals(o2)); } } qdox-qdox-1.12.1/src/test/com/thoughtworks/qdox/model/JavaPackageTest.java000066400000000000000000000004511204551233600265300ustar00rootroot00000000000000package com.thoughtworks.qdox.model; import junit.framework.TestCase; public class JavaPackageTest extends TestCase { public void testToStringJavaLang() throws Exception { JavaPackage pckg = new JavaPackage("java.lang"); assertEquals("package java.lang", pckg.toString()); } } qdox-qdox-1.12.1/src/test/com/thoughtworks/qdox/model/JavaParameterTest.java000066400000000000000000000007271204551233600271230ustar00rootroot00000000000000package com.thoughtworks.qdox.model; import junit.framework.TestCase; public class JavaParameterTest extends TestCase { public JavaParameterTest(String s) { super(s); } public void testParentMethod() throws Exception { JavaParameter p = new JavaParameter(new Type("x"), "x"); assertNull(p.getParentMethod()); JavaMethod m = new JavaMethod(); m.addParameter(p); assertSame(m, p.getParentMethod()); } } qdox-qdox-1.12.1/src/test/com/thoughtworks/qdox/model/JavaSourceTest.java000066400000000000000000000171401204551233600264400ustar00rootroot00000000000000package com.thoughtworks.qdox.model; import junit.framework.TestCase; import java.util.HashMap; public class JavaSourceTest extends TestCase { private JavaSource source; public JavaSourceTest(String s) { super(s); } protected void setUp() throws Exception { super.setUp(); source = new JavaSource(); source.setClassLibrary(new ClassLibrary()); } public void testToStringOneClass() throws Exception { JavaClass cls = new JavaClass(); cls.setName("MyClass"); source.addClass(cls); String expected = "" + "class MyClass {\n" + "\n" + "}\n"; assertEquals(expected, source.toString()); } public void testToStringMultipleClass() throws Exception { JavaClass cls1 = new JavaClass(); cls1.setName("MyClass1"); source.addClass(cls1); JavaClass cls2 = new JavaClass(); cls2.setName("MyClass2"); source.addClass(cls2); JavaClass cls3 = new JavaClass(); cls3.setName("MyClass3"); source.addClass(cls3); String expected = "" + "class MyClass1 {\n" + "\n" + "}\n" + "\n" + "class MyClass2 {\n" + "\n" + "}\n" + "\n" + "class MyClass3 {\n" + "\n" + "}\n"; assertEquals(expected, source.toString()); } public void testToStringPackage() throws Exception { JavaClass cls = new JavaClass(); cls.setName("MyClass"); source.addClass(cls); source.setPackage(new JavaPackage("com.thing", new HashMap())); String expected = "" + "package com.thing;\n" + "\n" + "class MyClass {\n" + "\n" + "}\n"; assertEquals(expected, source.toString()); } public void testToStringImport() throws Exception { JavaClass cls = new JavaClass(); cls.setName("MyClass"); source.addClass(cls); source.addImport("java.util.*"); String expected = "" + "import java.util.*;\n" + "\n" + "class MyClass {\n" + "\n" + "}\n"; assertEquals(expected, source.toString()); } public void testToStringMultipleImports() throws Exception { JavaClass cls = new JavaClass(); cls.setName("MyClass"); source.addClass(cls); source.addImport("java.util.*"); source.addImport("com.blah.Thing"); source.addImport("xxx"); String expected = "" + "import java.util.*;\n" + "import com.blah.Thing;\n" + "import xxx;\n" + "\n" + "class MyClass {\n" + "\n" + "}\n"; assertEquals(expected, source.toString()); } public void testToStringImportAndPackage() throws Exception { JavaClass cls = new JavaClass(); cls.setName("MyClass"); source.addClass(cls); source.addImport("java.util.*"); source.setPackage(new JavaPackage("com.moo", new HashMap())); String expected = "" + "package com.moo;\n" + "\n" + "import java.util.*;\n" + "\n" + "class MyClass {\n" + "\n" + "}\n"; assertEquals(expected, source.toString()); } public void testGetClassNamePrefix() { assertEquals("", source.getClassNamePrefix()); source.setPackage(new JavaPackage("foo.bar", new HashMap())); assertEquals("foo.bar.", source.getClassNamePrefix()); } public void testResolveJavaPrimitive() throws Exception { source.addImport("bogus.int"); source.addImport("bogus.double"); String[] primitives = new String[]{ "boolean", "byte", "char", "double", "float", "int", "long", "short", "void" }; for (int i = 0; i < primitives.length; i++) { assertEquals(primitives[i], source.resolveType(primitives[i])); } } public void testDontResolveMissingClasses() throws Exception { assertEquals(null, source.resolveType("not.Found")); } public void testResolveFullyQualifiedName() throws Exception { source.getClassLibrary().add("open.Bar"); assertEquals("open.Bar", source.resolveType("open.Bar")); } public void testResolveFullyQualifiedImport() throws Exception { source.addImport("foo.Bar"); source.getClassLibrary().add("foo.Bar"); assertEquals("foo.Bar", source.resolveType("Bar")); } public void testResolveChooseFirstMatchingImport() throws Exception { source.addImport("bogus.package.MyType"); source.addImport("com.thoughtworks.qdox.model.Type"); source.addImport("another.package.Type"); source.getClassLibrary().add("bogus.package.MyType"); source.getClassLibrary().add("com.thoughtworks.qdox.model.Type"); source.getClassLibrary().add("another.package.Type"); assertEquals("com.thoughtworks.qdox.model.Type", source.resolveType("Type")); } public void testResolveSamePackage() throws Exception { source.setPackage(new JavaPackage("foo", new HashMap())); source.getClassLibrary().add("foo.Bar"); assertEquals("foo.Bar", source.resolveType("Bar")); } public void testResolveFullyQualifiedTrumpsSamePackage() throws Exception { source.setPackage(new JavaPackage("foo", new HashMap())); source.getClassLibrary().add("foo.Bar"); source.getClassLibrary().add("open.Bar"); assertEquals("open.Bar", source.resolveType("open.Bar")); } public void testResolveFullyQualifiedTrumpsWildCard() throws Exception { source.addImport("bar.Bar"); source.addImport("foo.Bar"); source.getClassLibrary().add("foo.*"); source.getClassLibrary().add("bar.Bar"); assertEquals("bar.Bar", source.resolveType("Bar")); } public void testResolveWildcard() throws Exception { source.getClassLibrary().add("foo.Bar"); source.addImport("foo.*"); assertEquals("foo.Bar", source.resolveType("Bar")); } public void testResolveJavaLangClass() throws Exception { source.getClassLibrary().add("java.lang.System"); assertEquals("java.lang.System", source.resolveType("System")); } public void testResolveSamePackageTrumpsWildcard() throws Exception { source.addImport("com.thoughtworks.qdox.model.Type"); source.addImport("foo.*"); source.getClassLibrary().add("com.thoughtworks.qdox.model.Type"); source.getClassLibrary().add("foo.Type"); assertEquals("com.thoughtworks.qdox.model.Type", source.resolveType("Type")); } public void testResolveFullyQualifiedInnerClass() throws Exception { source.setPackage(new JavaPackage("foo", new HashMap())); source.getClassLibrary().add("foo.Bar$Fnord"); assertEquals("foo.Bar$Fnord", source.resolveType("foo.Bar.Fnord")); } public void testResolvePartiallySpecifiedInnerClass() throws Exception { source.setPackage(new JavaPackage("foo", new HashMap())); source.addImport("java.util.*"); source.getClassLibrary().add("foo.Bar$Fnord"); source.getClassLibrary().addDefaultLoader(); assertEquals("foo.Bar$Fnord", source.resolveType("Bar.Fnord")); assertEquals("java.util.Map$Entry", source.resolveType("Map.Entry")); } } qdox-qdox-1.12.1/src/test/com/thoughtworks/qdox/model/ModelBuilderTest.java000066400000000000000000000703121204551233600267450ustar00rootroot00000000000000package com.thoughtworks.qdox.model; import java.util.Arrays; import junit.framework.TestCase; import com.thoughtworks.qdox.parser.structs.ClassDef; import com.thoughtworks.qdox.parser.structs.FieldDef; import com.thoughtworks.qdox.parser.structs.MethodDef; import com.thoughtworks.qdox.parser.structs.PackageDef; import com.thoughtworks.qdox.parser.structs.TagDef; import com.thoughtworks.qdox.parser.structs.TypeDef; public class ModelBuilderTest extends TestCase { private ModelBuilder builder; public ModelBuilderTest(String s) { super(s); } protected void setUp() throws Exception { super.setUp(); builder = new ModelBuilder(); } public void testNumberOfClassesGrows() throws Exception { assertEquals(0, builder.getSource().getClasses().length); builder.beginClass(new ClassDef()); builder.endClass(); assertEquals(1, builder.getSource().getClasses().length); builder.beginClass(new ClassDef()); builder.endClass(); assertEquals(2, builder.getSource().getClasses().length); } public void testSimpleClass() throws Exception { ClassDef cls = new ClassDef(); cls.name = "Thingy"; builder.beginClass(cls); builder.endClass(); ClassDef cls2 = new ClassDef(); cls2.name = "ThingyThing"; builder.beginClass(cls2); builder.endClass(); JavaSource source = builder.getSource(); assertEquals("Thingy", source.getClasses()[0].getName()); assertEquals("ThingyThing", source.getClasses()[1].getName()); assertEquals(source, source.getClasses()[0].getParentSource()); } public void testInterface() throws Exception { ClassDef cls = new ClassDef(); builder.beginClass(cls); builder.endClass(); ClassDef cls2 = new ClassDef(); cls2.type = ClassDef.INTERFACE; builder.beginClass(cls2); builder.endClass(); JavaSource source = builder.getSource(); assertEquals(false, source.getClasses()[0].isInterface()); assertEquals(true, source.getClasses()[1].isInterface()); } public void testEnum() throws Exception { ClassDef cls = new ClassDef(); builder.beginClass(cls); builder.endClass(); ClassDef cls2 = new ClassDef(); cls2.type = ClassDef.ENUM; builder.beginClass(cls2); builder.endClass(); JavaSource source = builder.getSource(); assertEquals(false, source.getClasses()[0].isEnum()); assertEquals(true, source.getClasses()[1].isEnum()); } public void testAnnotationType() throws Exception { ClassDef cls = new ClassDef(); cls.type = ClassDef.ANNOTATION_TYPE; builder.beginClass(cls); builder.endClass(); JavaSource source = builder.getSource(); assertEquals(1, source.getClasses().length); } public void testClassExtends() throws Exception { ClassDef cls = new ClassDef(); builder.beginClass(cls); builder.endClass(); ClassDef cls2 = new ClassDef(); cls2.extendz.add(new TypeDef("Another")); builder.beginClass(cls2); builder.endClass(); builder.addImport("com.thoughtworks.*"); JavaSource source = builder.getSource(); assertEquals("java.lang.Object", source.getClasses()[0].getSuperClass().getValue()); assertEquals("Another", source.getClasses()[1].getSuperClass().getValue()); assertEquals(0, source.getClasses()[0].getImplements().length); assertEquals(0, source.getClasses()[1].getImplements().length); //Add another class and see if Another gets resolved builder.addPackage(new PackageDef("com.thoughtworks")); ClassDef anotherCls = new ClassDef(); anotherCls.name = "Another"; builder.beginClass(anotherCls); builder.endClass(); assertEquals("com.thoughtworks.Another", source.getClasses()[1].getSuperClass().getValue()); } public void testInterfaceExtends() throws Exception { ClassDef cls = new ClassDef(); cls.type = ClassDef.INTERFACE; builder.beginClass(cls); builder.endClass(); ClassDef cls2 = new ClassDef(); cls2.type = ClassDef.INTERFACE; cls2.extendz.add(new TypeDef("Another")); builder.beginClass(cls2); builder.endClass(); JavaSource source = builder.getSource(); assertEquals(0, source.getClasses()[0].getImplements().length); assertEquals(1, source.getClasses()[1].getImplements().length); assertEquals("Another", source.getClasses()[1].getImplements()[0].getValue()); assertNull(source.getClasses()[0].getSuperClass()); assertNull(source.getClasses()[1].getSuperClass()); } public void testInterfaceExtendsMultiple() throws Exception { ClassDef cls = new ClassDef(); cls.type = ClassDef.INTERFACE; cls.extendz.add(new TypeDef("Another")); cls.extendz.add(new TypeDef("java.io.Serializable")); cls.extendz.add(new TypeDef("BottleOpener")); builder.beginClass(cls); builder.endClass(); JavaSource source = builder.getSource(); // sorted Arrays.sort(source.getClasses()[0].getImplements()); assertEquals(3, source.getClasses()[0].getImplements().length); assertEquals("Another", source.getClasses()[0].getImplements()[0].getValue()); assertEquals("BottleOpener", source.getClasses()[0].getImplements()[1].getValue()); assertEquals("java.io.Serializable", source.getClasses()[0].getImplements()[2].getValue()); assertNull(source.getClasses()[0].getSuperClass()); } public void testClassImplements() throws Exception { ClassDef cls = new ClassDef(); builder.beginClass(cls); builder.endClass(); ClassDef cls2 = new ClassDef(); cls2.implementz.add(new TypeDef("SomeInterface")); builder.beginClass(cls2); builder.endClass(); JavaSource source = builder.getSource(); assertEquals(0, source.getClasses()[0].getImplements().length); assertEquals(1, source.getClasses()[1].getImplements().length); assertEquals("SomeInterface", source.getClasses()[1].getImplements()[0].getValue()); assertEquals("java.lang.Object", source.getClasses()[0].getSuperClass().getValue()); assertEquals("java.lang.Object", source.getClasses()[1].getSuperClass().getValue()); } public void testClassImplementsMultiple() throws Exception { ClassDef cls = new ClassDef(); cls.implementz.add(new TypeDef("SomeInterface")); cls.implementz.add(new TypeDef("XX")); builder.beginClass(cls); builder.endClass(); JavaSource source = builder.getSource(); assertEquals(2, source.getClasses()[0].getImplements().length); Arrays.sort(source.getClasses()[0].getImplements()); assertEquals("SomeInterface", source.getClasses()[0].getImplements()[0].getValue()); assertEquals("XX", source.getClasses()[0].getImplements()[1].getValue()); } public void testClassExtendsAndImplements() throws Exception { ClassDef cls = new ClassDef(); cls.extendz.add(new TypeDef("SubClass")); cls.implementz.add(new TypeDef("SomeInterface")); cls.implementz.add(new TypeDef("XX")); builder.beginClass(cls); builder.endClass(); JavaSource source = builder.getSource(); assertEquals(2, source.getClasses()[0].getImplements().length); Arrays.sort(source.getClasses()[0].getImplements()); assertEquals("SomeInterface", source.getClasses()[0].getImplements()[0].getValue()); assertEquals("XX", source.getClasses()[0].getImplements()[1].getValue()); assertEquals("SubClass", source.getClasses()[0].getSuperClass().getValue()); } public void testClassModifiers() throws Exception { builder.beginClass(new ClassDef()); builder.endClass(); ClassDef cls2 = new ClassDef(); cls2.modifiers.add("public"); cls2.modifiers.add("final"); builder.beginClass(cls2); builder.endClass(); JavaSource source = builder.getSource(); assertEquals(0, source.getClasses()[0].getModifiers().length); assertEquals(2, source.getClasses()[1].getModifiers().length); // sorted String[] modifiers = source.getClasses()[1].getModifiers(); Arrays.sort(modifiers); assertEquals("final", modifiers[0]); assertEquals("public", modifiers[1]); } public void testAddMethodsToCorrectClass() throws Exception { builder.beginClass(new ClassDef()); builder.addMethod(new MethodDef()); builder.endClass(); builder.beginClass(new ClassDef()); builder.addMethod(new MethodDef()); builder.addMethod(new MethodDef()); builder.addMethod(new MethodDef()); builder.endClass(); builder.beginClass(new ClassDef()); builder.addMethod(new MethodDef()); builder.addMethod(new MethodDef()); builder.endClass(); JavaSource source = builder.getSource(); assertEquals(1, source.getClasses()[0].getMethods().length); assertEquals(3, source.getClasses()[1].getMethods().length); assertEquals(2, source.getClasses()[2].getMethods().length); } public void testInnerClass() throws Exception { builder.addPackage(new PackageDef("xyz")); ClassDef outerDef = new ClassDef(); outerDef.name = "Outer"; builder.beginClass(outerDef); ClassDef innerDef = new ClassDef(); innerDef.name = "Inner"; builder.beginClass(innerDef); MethodDef fooDef = new MethodDef(); fooDef.name = "foo"; builder.addMethod(fooDef); builder.endClass(); MethodDef barDef = new MethodDef(); barDef.name = "bar"; builder.addMethod(barDef); builder.endClass(); JavaSource source = builder.getSource(); assertEquals(1, source.getClasses().length); JavaClass outerClass = source.getClasses()[0]; assertEquals("xyz.Outer", outerClass.getFullyQualifiedName()); assertEquals(1, outerClass.getMethods().length); assertEquals("bar", outerClass.getMethods()[0].getName()); assertEquals(1, outerClass.getNestedClasses().length); JavaClass innerClass = outerClass.getNestedClasses()[0]; assertEquals("xyz.Outer$Inner", innerClass.getFullyQualifiedName()); assertEquals(1, innerClass.getMethods().length); assertEquals("foo", innerClass.getMethods()[0].getName()); } public void testSimpleMethod() throws Exception { builder.beginClass(new ClassDef()); MethodDef mth = new MethodDef(); mth.name = "doSomething"; mth.returnType = new TypeDef("void"); builder.addMethod(mth); builder.endClass(); JavaSource source = builder.getSource(); JavaMethod doSomething = source.getClasses()[0].getMethods()[0]; assertEquals("doSomething", doSomething.getName()); assertEquals("void", doSomething.getReturns().getValue()); JavaSource parentSource = doSomething.getReturns().getJavaClassParent().getParentSource(); assertSame(source, parentSource); assertEquals(0, doSomething.getModifiers().length); assertEquals(0, doSomething.getParameters().length); assertEquals(0, doSomething.getExceptions().length); } public void testMethodNoArray() throws Exception { builder.beginClass(new ClassDef()); MethodDef mth = new MethodDef(); mth.name = "doSomething"; mth.returnType = new TypeDef("void"); mth.dimensions = 0; builder.addMethod(mth); builder.endClass(); JavaSource source = builder.getSource(); JavaMethod result = source.getClasses()[0].getMethods()[0]; assertEquals(0, result.getReturns().getDimensions()); } public void testMethod1dArray() throws Exception { builder.beginClass(new ClassDef()); MethodDef mth = new MethodDef(); mth.name = "doSomething"; mth.returnType = new TypeDef("void"); mth.dimensions = 1; builder.addMethod(mth); builder.endClass(); JavaSource source = builder.getSource(); JavaMethod result = source.getClasses()[0].getMethods()[0]; assertEquals(1, result.getReturns().getDimensions()); } public void testMethod2dArray() throws Exception { builder.beginClass(new ClassDef()); MethodDef mth = new MethodDef(); mth.name = "doSomething"; mth.returnType = new TypeDef("void"); mth.dimensions = 2; builder.addMethod(mth); builder.endClass(); JavaSource source = builder.getSource(); JavaMethod result = source.getClasses()[0].getMethods()[0]; assertEquals(2, result.getReturns().getDimensions()); } public void testMethodParameters() throws Exception { builder.beginClass(new ClassDef()); MethodDef mth = new MethodDef(); builder.addMethod(mth); FieldDef f1 = new FieldDef(); f1.name = "count"; f1.type = new TypeDef("int"); f1.modifiers.add("final"); builder.addParameter( f1 ); FieldDef f2 = new FieldDef(); f2.name = "name"; f2.type = new TypeDef("String"); builder.addParameter( f2 ); builder.endClass(); JavaSource source = builder.getSource(); JavaMethod result = source.getClasses()[0].getMethods()[0]; assertEquals(2, result.getParameters().length); assertEquals("count", result.getParameters()[0].getName()); assertEquals("int", result.getParameters()[0].getType().getValue()); assertEquals("name", result.getParameters()[1].getName()); assertEquals("String", result.getParameters()[1].getType().getValue()); } public void testMethodParametersWithArrays() throws Exception { builder.beginClass(new ClassDef()); MethodDef mth = new MethodDef(); builder.addMethod(mth); FieldDef f1 = new FieldDef(); f1.name = "count"; f1.type = new TypeDef("int"); f1.modifiers.add("final"); f1.dimensions = 1; builder.addParameter( f1 ); FieldDef f2 = new FieldDef(); f2.name = "name"; f2.type = new TypeDef("String"); f2.dimensions = 2; builder.addParameter( f2 ); builder.endClass(); JavaSource source = builder.getSource(); JavaMethod result = source.getClasses()[0].getMethods()[0]; assertEquals(1, result.getParameters()[0].getType().getDimensions()); assertEquals(2, result.getParameters()[1].getType().getDimensions()); } public void testMethodExceptions() throws Exception { builder.beginClass(new ClassDef()); MethodDef mth = new MethodDef(); mth.exceptions.add("RuntimeException"); mth.exceptions.add("java.io.IOException"); builder.addMethod(mth); builder.endClass(); JavaSource source = builder.getSource(); JavaMethod result = source.getClasses()[0].getMethods()[0]; assertEquals(2, result.getExceptions().length); // sorted Arrays.sort(result.getExceptions()); assertEquals("RuntimeException", result.getExceptions()[0].getValue()); assertEquals("java.io.IOException", result.getExceptions()[1].getValue()); } public void testMethodModifiers() throws Exception { builder.beginClass(new ClassDef()); MethodDef mth = new MethodDef(); mth.modifiers.add("public"); mth.modifiers.add("final"); mth.modifiers.add("synchronized"); builder.addMethod(mth); builder.endClass(); JavaSource source = builder.getSource(); JavaMethod result = source.getClasses()[0].getMethods()[0]; assertEquals(3, result.getModifiers().length); // sorted String[] modifiers = result.getModifiers(); Arrays.sort(modifiers); assertEquals("final", modifiers[0]); assertEquals("public", modifiers[1]); assertEquals("synchronized", modifiers[2]); } public void testSimpleField() throws Exception { builder.beginClass(new ClassDef()); FieldDef fld = new FieldDef(); fld.name = "count"; fld.type = new TypeDef("int"); builder.addField(fld); builder.endClass(); JavaSource source = builder.getSource(); JavaField result = source.getClasses()[0].getFields()[0]; assertNotNull(result); assertEquals("count", result.getName()); assertEquals("int", result.getType().getValue()); } public void testFieldWithModifiers() throws Exception { builder.beginClass(new ClassDef()); FieldDef fld = new FieldDef(); fld.modifiers.add("blah"); fld.modifiers.add("blah2"); builder.addField(fld); builder.endClass(); JavaSource source = builder.getSource(); JavaField result = source.getClasses()[0].getFields()[0]; assertNotNull(result); assertNotNull(result.getModifiers()); Arrays.sort(result.getModifiers()); assertEquals("blah2", result.getModifiers()[0]); assertEquals("blah", result.getModifiers()[1]); } public void testFieldNoArray() throws Exception { builder.beginClass(new ClassDef()); FieldDef fld = new FieldDef(); fld.name = "count"; fld.type = new TypeDef("int"); fld.dimensions = 0; builder.addField(fld); builder.endClass(); JavaSource source = builder.getSource(); JavaField result = source.getClasses()[0].getFields()[0]; assertEquals(0, result.getType().getDimensions()); } public void testField1dArray() throws Exception { builder.beginClass(new ClassDef()); FieldDef fld = new FieldDef(); fld.name = "count"; fld.type = new TypeDef("int"); fld.dimensions = 1; builder.addField(fld); builder.endClass(); JavaSource source = builder.getSource(); JavaField result = source.getClasses()[0].getFields()[0]; assertEquals(1, result.getType().getDimensions()); } public void testField2dArray() throws Exception { builder.beginClass(new ClassDef()); FieldDef fld = new FieldDef(); fld.name = "count"; fld.type = new TypeDef("int"); fld.dimensions = 2; builder.addField(fld); builder.endClass(); JavaSource source = builder.getSource(); JavaField result = source.getClasses()[0].getFields()[0]; assertEquals(2, result.getType().getDimensions()); } public void testSimpleConstructor() throws Exception { builder.beginClass(new ClassDef()); MethodDef mth = new MethodDef(); mth.name = "MyClass"; mth.constructor = true; builder.addMethod(mth); MethodDef mth2 = new MethodDef(); mth2.name = "method"; mth2.returnType = new TypeDef("void"); builder.addMethod(mth2); builder.endClass(); JavaSource source = builder.getSource(); JavaMethod result1 = source.getClasses()[0].getMethods()[0]; JavaMethod result2 = source.getClasses()[0].getMethods()[1]; assertTrue(result1.isConstructor()); assertNull(result1.getReturns()); assertTrue(!result2.isConstructor()); assertNotNull(result2.getReturns()); } public void testJavaDocOnClass() throws Exception { builder.addJavaDoc("Hello"); builder.beginClass(new ClassDef()); builder.endClass(); JavaSource source = builder.getSource(); assertEquals("Hello", source.getClasses()[0].getComment()); } public void testJavaDocSpiradiclyOnManyClasses() throws Exception { builder.addJavaDoc("Hello"); builder.beginClass(new ClassDef()); builder.endClass(); builder.beginClass(new ClassDef()); builder.endClass(); builder.addJavaDoc("World"); builder.beginClass(new ClassDef()); builder.endClass(); JavaSource source = builder.getSource(); assertEquals("Hello", source.getClasses()[0].getComment()); assertNull(source.getClasses()[1].getComment()); assertEquals("World", source.getClasses()[2].getComment()); } public void testJavaDocOnMethod() throws Exception { builder.beginClass(new ClassDef()); builder.addJavaDoc("Hello"); builder.addMethod(new MethodDef()); builder.endClass(); JavaSource source = builder.getSource(); assertNull(source.getClasses()[0].getComment()); assertEquals("Hello", source.getClasses()[0].getMethods()[0].getComment()); } public void testJavaDocOnField() throws Exception { builder.beginClass(new ClassDef()); builder.addJavaDoc("Hello"); builder.addField(new FieldDef()); builder.endClass(); JavaSource source = builder.getSource(); assertNull(source.getClasses()[0].getComment()); assertEquals("Hello", source.getClasses()[0].getFields()[0].getComment()); } public void testJavaDocOnMethodsAndFields() throws Exception { builder.addJavaDoc("Thing"); builder.beginClass(new ClassDef()); builder.addField(new FieldDef());// f0 builder.addJavaDoc("Hello"); builder.addMethod(new MethodDef());//m0 builder.addJavaDoc("Hello field"); builder.addField(new FieldDef());//f1 builder.addMethod(new MethodDef());//m1 builder.addJavaDoc("World"); builder.addMethod(new MethodDef());//m2 builder.endClass(); JavaSource source = builder.getSource(); assertEquals("Thing", source.getClasses()[0].getComment()); assertNull(source.getClasses()[0].getFields()[0].getComment()); assertEquals("Hello field", source.getClasses()[0].getFields()[1].getComment()); assertEquals("Hello", source.getClasses()[0].getMethods()[0].getComment()); assertNull(source.getClasses()[0].getMethods()[1].getComment()); assertEquals("World", source.getClasses()[0].getMethods()[2].getComment()); } public void testDocletTag() throws Exception { builder.addJavaDoc("Hello"); builder.addJavaDocTag(new TagDef("cheese", "is good")); builder.beginClass(new ClassDef()); builder.endClass(); JavaSource source = builder.getSource(); assertEquals("Hello", source.getClasses()[0].getComment()); assertEquals(1, source.getClasses()[0].getTags().length); assertEquals("cheese", source.getClasses()[0].getTags()[0].getName()); assertEquals("is good", source.getClasses()[0].getTags()[0].getValue()); } public void testDocletTagWithNoComment() throws Exception { builder.addJavaDoc(""); // parser will always call this method to signify start of javadoc builder.addJavaDocTag(new TagDef("cheese", "is good")); builder.beginClass(new ClassDef()); builder.endClass(); JavaSource source = builder.getSource(); assertEquals("", source.getClasses()[0].getComment()); assertEquals(1, source.getClasses()[0].getTags().length); assertEquals("cheese", source.getClasses()[0].getTags()[0].getName()); assertEquals("is good", source.getClasses()[0].getTags()[0].getValue()); } public void testMultipleDocletTags() throws Exception { builder.addJavaDoc("Hello"); builder.addJavaDocTag(new TagDef("cheese", "is good")); builder.addJavaDocTag(new TagDef("food", "is great")); builder.addJavaDocTag(new TagDef("chairs", "are boring")); builder.beginClass(new ClassDef()); builder.endClass(); JavaSource source = builder.getSource(); assertEquals("Hello", source.getClasses()[0].getComment()); assertEquals(3, source.getClasses()[0].getTags().length); assertEquals("cheese", source.getClasses()[0].getTags()[0].getName()); assertEquals("is good", source.getClasses()[0].getTags()[0].getValue()); assertEquals("food", source.getClasses()[0].getTags()[1].getName()); assertEquals("is great", source.getClasses()[0].getTags()[1].getValue()); assertEquals("chairs", source.getClasses()[0].getTags()[2].getName()); assertEquals("are boring", source.getClasses()[0].getTags()[2].getValue()); } public void testDocletTagsOnMethodsAndFields() throws Exception { builder.addJavaDoc(""); builder.addJavaDocTag(new TagDef("cheese", "is good")); builder.beginClass(new ClassDef()); builder.addJavaDoc(""); builder.addJavaDocTag(new TagDef("food", "is great")); builder.addMethod(new MethodDef()); builder.addJavaDoc(""); builder.addJavaDocTag(new TagDef("chairs", "are boring")); builder.addField(new FieldDef()); builder.endClass(); JavaSource source = builder.getSource(); assertEquals("cheese", source.getClasses()[0].getTags()[0].getName()); assertEquals("is good", source.getClasses()[0].getTags()[0].getValue()); assertEquals("food", source.getClasses()[0].getMethods()[0].getTags()[0].getName()); assertEquals("is great", source.getClasses()[0].getMethods()[0].getTags()[0].getValue()); assertEquals("chairs", source.getClasses()[0].getFields()[0].getTags()[0].getName()); assertEquals("are boring", source.getClasses()[0].getFields()[0].getTags()[0].getValue()); } public void testRetrieveJavaSource() throws Exception { builder.beginClass(new ClassDef()); builder.endClass(); JavaSource source = builder.getSource(); assertNotNull(source); } public void testJavaSourceClassCount() throws Exception { builder.beginClass(new ClassDef()); builder.endClass(); builder.beginClass(new ClassDef()); builder.endClass(); builder.beginClass(new ClassDef()); builder.endClass(); JavaSource result = builder.getSource(); assertEquals(3, result.getClasses().length); } public void testJavaSourceNoPackage() throws Exception { JavaSource result = builder.getSource(); assertNull(result.getPackage()); } public void testJavaSourceWithPackage() throws Exception { builder.addPackage(new PackageDef("com.blah.thing")); JavaSource result = builder.getSource(); assertEquals("com.blah.thing", result.getPackage().getName()); } public void testJavaSourceNoImports() throws Exception { JavaSource result = builder.getSource(); assertEquals(0, result.getImports().length); } public void testJavaSourceOneImport() throws Exception { builder.addImport("com.blah.Thing"); JavaSource result = builder.getSource(); assertEquals(1, result.getImports().length); assertEquals("com.blah.Thing", result.getImports()[0]); } public void testJavaSourceMultipleImports() throws Exception { builder.addImport("com.blah.Thing"); builder.addImport("java.util.List"); builder.addImport("org.apache.*"); JavaSource result = builder.getSource(); assertEquals(3, result.getImports().length); assertEquals("com.blah.Thing", result.getImports()[0]); assertEquals("java.util.List", result.getImports()[1]); assertEquals("org.apache.*", result.getImports()[2]); } public void testModelHashCodes() { ClassDef classDef = new ClassDef(); classDef.name = "hello"; assertTrue(classDef.hashCode() > 0); MethodDef methodDef = new MethodDef(); methodDef.name = "hello"; assertTrue(methodDef.hashCode() > 0); FieldDef fieldDef = new FieldDef(); fieldDef.name = "hello"; assertTrue(fieldDef.hashCode() > 0); JavaParameter javaParameter = new JavaParameter(new Type("q"), "w"); assertTrue(javaParameter.hashCode() > 0); } public void testType() { Type type1 = new Type("fred", 1); Type type2 = new Type("fred", 1); Type type3 = new Type("wilma", 2); assertTrue(type1.compareTo(type2) == 0); assertFalse(type1.compareTo(type3) == 0); assertTrue(type1.compareTo("barney") == 0); } } qdox-qdox-1.12.1/src/test/com/thoughtworks/qdox/model/TypeTest.java000066400000000000000000000062451204551233600253230ustar00rootroot00000000000000package com.thoughtworks.qdox.model; import java.io.StringReader; import junit.framework.TestCase; import com.thoughtworks.qdox.JavaClassContext; import com.thoughtworks.qdox.JavaDocBuilder; public class TypeTest extends TestCase { public TypeTest(String s) { super(s); } public void testResolving() throws Exception { ClassLibrary classLib = new ClassLibrary(); JavaSource src = new JavaSource(); src.setClassLibrary(classLib); src.addImport("foo.*"); Type type = Type.createUnresolved("Bar", 0, src); assertEquals(false, type.isResolved()); classLib.add("foo.Bar"); assertEquals(true, type.isResolved()); assertEquals("foo.Bar", type.getValue()); } public void testArrayType() throws Exception { Type type = new Type("int", 1); assertTrue(type.isArray()); } public void testToString() throws Exception { assertEquals("int", new Type("int").toString()); assertEquals("int[]", new Type("int", 1).toString()); assertEquals("long[][][]", new Type("long", 3).toString()); } public void testEquals() throws Exception { assertEquals(new Type("string"), new Type("string")); assertNotEquals(new Type("string"), new Type("int")); assertNotEquals(new Type("long", 1), new Type("long")); assertNotEquals(new Type("long"), new Type("long", 2)); assertFalse(new Type("int").equals(null)); } public void testTypeHasJavaClass() { JavaSource javaSource = new JavaSource(new JavaClassContext(new JavaDocBuilder())); javaSource.setClassLibrary(new ClassLibrary()); Type type = new Type("java.util.HashSet", 0, javaSource); JavaClass clazz = type.getJavaClass(); JavaClass superClass = clazz.getSuperJavaClass(); assertEquals("java.util.AbstractSet", superClass.getFullyQualifiedName()); } public void testIsPrimitive() throws Exception { ClassLibrary classLibrary = new ClassLibrary( ClassLoader.getSystemClassLoader() ); JavaDocBuilder builder = new JavaDocBuilder(classLibrary); JavaClass javaClass = builder.getClassByName("java.lang.Object"); assertEquals(true, javaClass.getMethodBySignature("notify", null).getReturns().isPrimitive()); } public void testInnerClassToString() { ClassLibrary classLibrary = new ClassLibrary( ClassLoader.getSystemClassLoader() ); String source = "public class Outer {\n" + " private Inner ia;" + " public class Inner { }" + "}"; JavaDocBuilder builder = new JavaDocBuilder(classLibrary); builder.addSource( new StringReader( source ) ); assertEquals("Outer.Inner", builder.getClassByName( "Outer" ).getFieldByName( "ia" ).getType().toString()); assertEquals("Outer.Inner", builder.getClassByName( "Outer" ).getFieldByName( "ia" ).getType().toGenericString()); } private void assertNotEquals(Object o1, Object o2) { assertTrue(o2.toString() + " should not equal " + o1.toString(), !o2.equals(o1)); } } qdox-qdox-1.12.1/src/test/com/thoughtworks/qdox/model/util/000077500000000000000000000000001204551233600236455ustar00rootroot00000000000000qdox-qdox-1.12.1/src/test/com/thoughtworks/qdox/model/util/OrderedMapTest.java000066400000000000000000000035761204551233600274050ustar00rootroot00000000000000package com.thoughtworks.qdox.model.util; import java.util.Iterator; import junit.framework.TestCase; public class OrderedMapTest extends TestCase { OrderedMap orderedMap = new OrderedMap(); public void testEmptyMap() { assertEquals(0, orderedMap.size()); assertEquals(0, orderedMap.entrySet().size()); assertEquals(false, orderedMap.entrySet().iterator().hasNext()); } public void testAddOneEntry() { orderedMap.put("foo", "bar"); assertEquals(1, orderedMap.size()); assertEquals(1, orderedMap.entrySet().size()); assertEquals(true, orderedMap.entrySet().iterator().hasNext()); assertEquals("bar", orderedMap.get("foo")); assertTrue(orderedMap.keySet().contains("foo")); assertTrue(orderedMap.values().contains("bar")); } public void testAddTwoEntries() { orderedMap.put("foo", "bar"); orderedMap.put("bork", "flarg"); assertEquals(2, orderedMap.size()); assertEquals(2, orderedMap.entrySet().size()); assertEquals("bar", orderedMap.get("foo")); assertEquals("flarg", orderedMap.get("bork")); } public void testEntryIsReplacedWhenKeysCollide() { orderedMap.put("tweedle", "dum"); assertEquals("dum",orderedMap.put("tweedle", "dee")); assertEquals("dee", orderedMap.get("tweedle")); assertEquals(1, orderedMap.size()); } public void testEntriesAreReturnedInOrderAdded() { orderedMap.put("juan", "x"); orderedMap.put("twoo", "x"); orderedMap.put("juan", "x"); orderedMap.put("free", "x"); Iterator keyIterator = orderedMap.keySet().iterator(); assertEquals("juan", keyIterator.next()); assertEquals("twoo", keyIterator.next()); assertEquals("free", keyIterator.next()); assertEquals(false, keyIterator.hasNext()); } } qdox-qdox-1.12.1/src/test/com/thoughtworks/qdox/model/util/SerializationUtils.java000066400000000000000000000025671204551233600303600ustar00rootroot00000000000000package com.thoughtworks.qdox.model.util; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; public class SerializationUtils { public static byte[] serialize(Object obj) { try { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(buffer); oos.writeObject(obj); oos.close(); return buffer.toByteArray(); } catch (IOException e) { e.printStackTrace(); throw new RuntimeException("error writing to byte-array!"); } } public static Object deserialize(byte[] bytes) throws ClassNotFoundException { try { ByteArrayInputStream input = new ByteArrayInputStream(bytes); ObjectInputStream ois = new ObjectInputStream(input); return ois.readObject(); } catch (IOException e) { e.printStackTrace(); throw new RuntimeException("error reading from byte-array!"); } } public static Object serializedCopy(Object obj) { try { return deserialize(serialize(obj)); } catch (ClassNotFoundException e) { throw new RuntimeException("this shouldn't happen"); } } }qdox-qdox-1.12.1/src/test/com/thoughtworks/qdox/model/util/TagParserTest.java000066400000000000000000000146551204551233600272530ustar00rootroot00000000000000package com.thoughtworks.qdox.model.util; import java.io.IOException; import java.io.StreamTokenizer; import java.util.Iterator; import java.util.Map; import junit.framework.TestCase; public class TagParserTest extends TestCase { public TagParserTest(String name) { super(name); } //---( Parse into named parameters )--- public void testEmptyInputContainsNoNamedParameters() { Map paramMap = TagParser.parseNamedParameters(""); assertNotNull(paramMap); assertTrue(paramMap.isEmpty()); } public void testMyUnderstandingOfStreamTokenizer() throws IOException { String input = "x=y 'foo' \" bar \" 234\t'multi\\\nline'\n" + "dotted.words hypen-ated under_scored"; StreamTokenizer tokenizer = TagParser.makeTokenizer(input); assertEquals(StreamTokenizer.TT_WORD, tokenizer.nextToken()); assertEquals("x", tokenizer.sval); assertEquals('=', tokenizer.nextToken()); assertEquals(StreamTokenizer.TT_WORD, tokenizer.nextToken()); assertEquals("y", tokenizer.sval); assertEquals('\'', tokenizer.nextToken()); assertEquals("foo", tokenizer.sval); assertEquals('"', tokenizer.nextToken()); assertEquals(" bar ", tokenizer.sval); assertEquals(StreamTokenizer.TT_WORD, tokenizer.nextToken()); assertEquals("234", tokenizer.sval); assertEquals('\'', tokenizer.nextToken()); assertEquals("multi\nline", tokenizer.sval); assertEquals(StreamTokenizer.TT_WORD, tokenizer.nextToken()); assertEquals("dotted.words", tokenizer.sval); assertEquals(StreamTokenizer.TT_WORD, tokenizer.nextToken()); assertEquals("hypen-ated", tokenizer.sval); assertEquals(StreamTokenizer.TT_WORD, tokenizer.nextToken()); assertEquals("under_scored", tokenizer.sval); } public void testCanParseSimpleNamedParameters() { Map paramMap = TagParser.parseNamedParameters("x=foo"); assertNotNull(paramMap); assertEquals(1, paramMap.size()); assertEquals("foo", paramMap.get("x")); } public void testCanParseMultipleNamedParameters() { Map paramMap = TagParser.parseNamedParameters("x=foo y=bar"); assertNotNull(paramMap); assertEquals(2, paramMap.size()); assertEquals("foo", paramMap.get("x")); assertEquals("bar", paramMap.get("y")); } public void testNamedParametersAreReturnedInOrderDeclared() { Map paramMap = TagParser.parseNamedParameters( "x=foo y=bar a=orses b=oney" ); assertEquals(4, paramMap.size()); Iterator keyIterator = paramMap.keySet().iterator(); assertEquals("x", keyIterator.next()); assertEquals("y", keyIterator.next()); assertEquals("a", keyIterator.next()); assertEquals("b", keyIterator.next()); } public void testNamedParameterValuesCanBeSingleQuoted() { Map paramMap = TagParser.parseNamedParameters("x='foo' y='bar fly'"); assertNotNull(paramMap); assertEquals(2, paramMap.size()); assertEquals("foo", paramMap.get("x")); assertEquals("bar fly", paramMap.get("y")); } public void testNamedParameterValuesCanBeDoubleQuoted() { Map paramMap = TagParser.parseNamedParameters("x=\"'foo'\" y=\"bar fly\""); assertNotNull(paramMap); assertEquals(2, paramMap.size()); assertEquals("'foo'", paramMap.get("x")); assertEquals("bar fly", paramMap.get("y")); } public void testNamedParametersCanHaveSpacesAroundEquals() { Map paramMap = TagParser.parseNamedParameters("x = foo y = 'bar'"); assertNotNull(paramMap); assertEquals(2, paramMap.size()); assertEquals("foo", paramMap.get("x")); assertEquals("bar", paramMap.get("y")); } public void testNamedParameterNamesCanContainHypensEtc() { Map paramMap = TagParser.parseNamedParameters("x.a = '1' x-b = '2' x_c = '3'"); assertNotNull(paramMap); assertEquals(3, paramMap.size()); assertEquals("1", paramMap.get("x.a")); assertEquals("2", paramMap.get("x-b")); assertEquals("3", paramMap.get("x_c")); } public void testNamedParameterValuesCanBeNumeric() { Map paramMap = TagParser.parseNamedParameters("x=1 y=2"); assertNotNull(paramMap); assertEquals(2, paramMap.size()); assertEquals("1", paramMap.get("x")); assertEquals("2", paramMap.get("y")); } public void testNamedParameterValuesCanSpanLinesIfBackslashIsUsed() { Map paramMap = TagParser.parseNamedParameters("x='multiline\\\nvalue'"); assertNotNull(paramMap); assertEquals(1, paramMap.size()); assertEquals("multiline\nvalue", paramMap.get("x")); } //---( Parse into "words": positional parameters )--- public void testEmptyInputContainsNoWords() { String[] words = TagParser.parseWords(""); assertEquals(0, words.length); } public void testCanSplitIntoWordsOnWhitespace() { String[] words = TagParser.parseWords("a b c"); assertEquals(3, words.length); assertEquals("a", words[0]); assertEquals("b", words[1]); assertEquals("c", words[2]); } public void testWordsCanContainHyphensEtc() { String[] words = TagParser.parseWords("a.b c-d e_f"); assertEquals(3, words.length); assertEquals("a.b", words[0]); assertEquals("c-d", words[1]); assertEquals("e_f", words[2]); } public void testMostPunctuationAreSeparateWords() { String[] words = TagParser.parseWords("a=c"); assertEquals(3, words.length); assertEquals("a", words[0]); assertEquals("=", words[1]); assertEquals("c", words[2]); } public void testShouldParseMultiLineParameters() { String[] words = TagParser.parseWords("\n" + "a=c\n" + "e=g\n"); assertEquals(6, words.length); assertEquals("a", words[0]); assertEquals("=", words[1]); assertEquals("c", words[2]); assertEquals("e", words[3]); assertEquals("=", words[4]); assertEquals("g", words[5]); } //for QDOX-173 public void testGenericsSupport() throws Exception { String[] words = TagParser.parseWords(" The Key"); assertEquals("", words[0]); assertEquals("The", words[1]); assertEquals("Key", words[2]); } } qdox-qdox-1.12.1/src/test/com/thoughtworks/qdox/parser/000077500000000000000000000000001204551233600230645ustar00rootroot00000000000000qdox-qdox-1.12.1/src/test/com/thoughtworks/qdox/parser/LexerTest.java000066400000000000000000000655311204551233600256600ustar00rootroot00000000000000package com.thoughtworks.qdox.parser; import junit.framework.TestCase; import java.io.FileReader; import java.io.IOException; import java.io.StringReader; import java.lang.reflect.Field; import java.util.HashMap; import java.util.Map; import com.thoughtworks.qdox.parser.impl.JFlexLexer; import com.thoughtworks.qdox.parser.impl.Parser; public class LexerTest extends TestCase { private static Map tokens; static { tokens = new HashMap(); Field[] tokenFlds = Parser.class.getDeclaredFields(); for (int i = 0; i < tokenFlds.length; i++) { Field f = tokenFlds[i]; try { if (!f.getName().startsWith("YY")) { tokens.put(new Integer(f.getShort(Parser.class)), f.getName()); } } catch (Exception e) { // we don't care! } } } public LexerTest(String s) { super(s); } public void testEmptyInput() throws Exception { String in = ""; Lexer lexer = new JFlexLexer(new StringReader(in)); assertLex(0, lexer); } public void testNewlines() throws Exception { String in = "DOS\r\nUNIX\nMAC\r"; Lexer lexer = new JFlexLexer(new StringReader(in)); assertLex(Parser.IDENTIFIER, "DOS", lexer); assertLex(Parser.IDENTIFIER, "UNIX", lexer); assertLex(Parser.IDENTIFIER, "MAC", lexer); assertLex(0, lexer); } public void testStaticBlock() throws Exception { String in = "" + "class X { " + " static { " + " something(); " + " } " + "} "; Lexer lexer = new JFlexLexer(new StringReader(in)); assertLex(Parser.CLASS, lexer); assertLex(Parser.IDENTIFIER, lexer); assertLex(Parser.BRACEOPEN, lexer); assertLex(Parser.STATIC, lexer); assertLex(Parser.CODEBLOCK, lexer); assertLex(Parser.BRACECLOSE, lexer); assertLex(0, lexer); } public void testFieldAssignment() throws Exception { checkAssignment("x"); checkAssignment("(map.isEmpty ? 1 : -1)"); checkAssignment("0"); checkAssignment("\"hello\""); checkAssignment("new Thingy()"); checkAssignment("new Thingy(\"xxx\", 3, x.getBlah())"); checkAssignment("new Thingy(\"xx;x\", 3, x.getBlah())"); checkAssignment("StaticClass.intance()"); checkAssignment("[1,2,3]"); checkAssignment("/* , ; } */"); } public void testAnonymousInnerClassAssignment() throws Exception { checkAssignment("new Thingifier() { void doThings(int x) { blah(); } }"); checkAssignment("new Thingifier() { void doThings(int x) { a = \"aaa\"; } }"); } public void testGenericTypeAssignment() throws Exception { // QDOX-77 checkAssignment("new HashMap"); } public void testFieldsContainingLessThanOrGreaterThanInAssignment() throws Exception { // QDOX-71 - this is really important as it is common to see in all versions of the JDK. // Please don't disable this test -joe. checkAssignment("x < y"); checkAssignment("x > y"); checkAssignment("x << y"); checkAssignment("x >> y"); checkAssignment("xz"); } private void checkAssignment(String assignment) throws IOException { String in = "" + "class X { " + " int x = " + assignment + "; " + "} "; Lexer lexer = new JFlexLexer(new StringReader(in)); assertLex(Parser.CLASS, lexer); assertLex(Parser.IDENTIFIER, lexer); assertLex(Parser.BRACEOPEN, lexer); assertLex(Parser.IDENTIFIER, "int", lexer); assertLex(Parser.IDENTIFIER, "x", lexer); assertLex(Parser.SEMI, lexer); assertLex(Parser.BRACECLOSE, lexer); assertLex(0, lexer); } public void testMultipleFields() throws Exception { String in = "" + "class X { " + " int x, y = 2; " + "} "; Lexer lexer = new JFlexLexer(new StringReader(in)); assertLex(Parser.CLASS, lexer); assertLex(Parser.IDENTIFIER, lexer); assertLex(Parser.BRACEOPEN, lexer); assertLex(Parser.IDENTIFIER, "int", lexer); assertLex(Parser.IDENTIFIER, "x", lexer); assertLex(Parser.COMMA, lexer); assertLex(Parser.IDENTIFIER, "y", lexer); assertLex(Parser.SEMI, lexer); assertLex(Parser.BRACECLOSE, lexer); assertLex(0, lexer); } public void testSpecialCharsInIdentifier() throws Exception { String in = "a_b x$y z80"; Lexer lexer = new JFlexLexer(new StringReader(in)); assertLex(Parser.IDENTIFIER, "a_b", lexer); assertLex(Parser.IDENTIFIER, "x$y", lexer); assertLex(Parser.IDENTIFIER, "z80", lexer); assertLex(0, lexer); } public void testUnicodeInTest() throws Exception { checkAssignment("\"\u0000\""); } public void testUnicodeInFile() throws Exception { Lexer lexer = new JFlexLexer(new FileReader("src/test/com/thoughtworks/qdox/testdata/Unicode.java")); assertLex(Parser.PACKAGE, lexer); assertLex(Parser.IDENTIFIER, lexer); assertLex(Parser.DOT, lexer); assertLex(Parser.IDENTIFIER, lexer); assertLex(Parser.DOT, lexer); assertLex(Parser.IDENTIFIER, lexer); assertLex(Parser.DOT, lexer); assertLex(Parser.IDENTIFIER, lexer); assertLex(Parser.SEMI, lexer); assertLex(Parser.CLASS, lexer); assertLex(Parser.IDENTIFIER, lexer); assertLex(Parser.BRACEOPEN, lexer); assertLex(Parser.IDENTIFIER, "String", lexer); assertLex(Parser.IDENTIFIER, "x", lexer); assertLex(Parser.SEMI, lexer); assertLex(Parser.BRACECLOSE, lexer); assertLex(0, lexer); } public void testUnicodeIdentifiers() throws Exception { // \u0391 == uppercase Greek "Alpha" assertSingleLex("\u0391", Parser.IDENTIFIER); // \u00f6 == lowercase o + diaeresis assertSingleLex("f\u00f6rnamn", Parser.IDENTIFIER); } public void testInnerClass() throws Exception { String in = "" + "class X { " + " class InnerClass { " + " int x = 1; " + " } " + " int y = 2; " + "} "; Lexer lexer = new JFlexLexer(new StringReader(in)); assertLex(Parser.CLASS, lexer); assertLex(Parser.IDENTIFIER, lexer); assertLex(Parser.BRACEOPEN, lexer); assertLex(Parser.CLASS, lexer); assertLex(Parser.IDENTIFIER, "InnerClass", lexer); assertLex(Parser.BRACEOPEN, lexer); assertLex(Parser.IDENTIFIER, "int", lexer); assertLex(Parser.IDENTIFIER, "x", lexer); assertLex(Parser.SEMI, lexer); assertLex(Parser.BRACECLOSE, lexer); assertLex(Parser.IDENTIFIER, "int", lexer); assertLex(Parser.IDENTIFIER, "y", lexer); assertLex(Parser.SEMI, lexer); assertLex(Parser.BRACECLOSE, lexer); assertLex(0, lexer); } public void testCurliesInStringsOrChars() throws Exception { checkAssignment("\"{\""); checkAssignment("\"}\""); checkAssignment("'}'"); checkAssignment("'{'"); } public void testDoubleBackSlashesInStringsOrChars() throws Exception { checkAssignment("\"\\\\\""); // x = "\\" checkAssignment("'\\\\'"); // x = '\\' } public void testFunnyCharsInStringsOrChars() throws Exception { checkAssignment("\"???????????\""); checkAssignment("'???????????'"); } public void testQuoteInCharInCodeBlock() throws Exception { String in = "{'\"'}"; Lexer lexer = new JFlexLexer(new StringReader(in)); assertLex(Parser.CODEBLOCK, lexer); assertLex(0, lexer); } public void testDoubleQuotesInCharInAssignment() throws Exception { String in = "x = '\"';"; Lexer lexer = new JFlexLexer(new StringReader(in)); assertLex(Parser.IDENTIFIER, "x", lexer); assertLex(Parser.SEMI, lexer); assertLex(0, lexer); } public void testSingleQuoteInCharInAssignment() throws Exception { String in = "x = '\\'';"; Lexer lexer = new JFlexLexer(new StringReader(in)); assertLex(Parser.IDENTIFIER, "x", lexer); assertLex(Parser.SEMI, lexer); assertLex(0, lexer); } public void testStringWithDoubleQuotesIn() throws Exception { String in = "x = \"blah \\\" blah\";"; Lexer lexer = new JFlexLexer(new StringReader(in)); assertLex(Parser.IDENTIFIER, "x", lexer); assertLex(Parser.SEMI, lexer); assertLex(0, lexer); } public void testCommentsWithSingleQuoteInCodeBlock() throws Exception { String in = "{ /* ' */ }"; Lexer lexer = new JFlexLexer(new StringReader(in)); assertLex(Parser.CODEBLOCK, lexer); assertLex(0, lexer); } public void testCommentsWithDoubleQuotesInCodeBlock() throws Exception { String in = "{ /* \" */ }"; Lexer lexer = new JFlexLexer(new StringReader(in)); assertLex(Parser.CODEBLOCK, lexer); assertLex(0, lexer); } public void testCommentsThatEndImmediately() throws Exception { String in = "/**/ class"; Lexer lexer = new JFlexLexer(new StringReader(in)); assertLex(Parser.CLASS, lexer); assertLex(0, lexer); } public void testCommentsWithQuotesInAssignment() throws Exception { String in = "a x = y /* don't do stuff*/;"; Lexer lexer = new JFlexLexer(new StringReader(in)); assertLex(Parser.IDENTIFIER, "a", lexer); assertLex(Parser.IDENTIFIER, "x", lexer); assertLex(Parser.SEMI, lexer); assertLex(0, lexer); in = "a z = \n" + "// thing's thing \n" + "0;"; lexer = new JFlexLexer(new StringReader(in)); assertLex(Parser.IDENTIFIER, "a", lexer); assertLex(Parser.IDENTIFIER, "z", lexer); assertLex(Parser.SEMI, lexer); assertLex(0, lexer); } public void testDocletTags() throws Exception { String in = "" + "/**\n" + " * @hello world\n" + " * @a b c d\n" + " * @bye\n" + " * @bye:bye\n" + " */"; Lexer lexer = new JFlexLexer(new StringReader(in)); assertLex(Parser.JAVADOCSTART, lexer); assertLex(Parser.JAVADOCLINE, "\n",lexer); assertLex(Parser.JAVADOCTAG, "@hello", lexer); assertLex(Parser.JAVADOCLINE, "world\n", lexer); assertLex(Parser.JAVADOCTAG, "@a", lexer); assertLex(Parser.JAVADOCLINE, "b c d\n", lexer); assertLex(Parser.JAVADOCTAG, "@bye", lexer); assertLex(Parser.JAVADOCLINE, "\n",lexer); assertLex(Parser.JAVADOCTAG, "@bye:bye", lexer); assertLex(Parser.JAVADOCLINE, "\n",lexer); assertLex(Parser.JAVADOCEND, lexer); assertLex(0, lexer); } public void testOneLinerDocComment() throws Exception { String in = "/** @hello world */"; Lexer lexer = new JFlexLexer(new StringReader(in)); assertLex(Parser.JAVADOCSTART, lexer); assertLex(Parser.JAVADOCTAG, "@hello", lexer); assertLex(Parser.JAVADOCLINE, "world", lexer); assertLex(Parser.JAVADOCEND, lexer); assertLex(0, lexer); } public void testCompressedDocComment() throws Exception { String in = "/**@foo bar*/"; Lexer lexer = new JFlexLexer(new StringReader(in)); assertLex(Parser.JAVADOCSTART, lexer); assertLex(Parser.JAVADOCTAG, "@foo", lexer); assertLex(Parser.JAVADOCLINE, "bar", lexer); assertLex(Parser.JAVADOCEND, lexer); assertLex(0, lexer); } public void testDeepJavadocTag() throws Exception { String in = " /** * *** * @m x \n" + "*/"; Lexer lexer = new JFlexLexer(new StringReader(in)); assertLex(Parser.JAVADOCSTART, lexer); assertLex(Parser.JAVADOCLINE, "* *** * @m x \n", lexer); assertLex(Parser.JAVADOCEND, lexer); assertLex(0, lexer); } public void testDocCommentContainingAtSymbols() throws Exception { String in = "" + "/**\n" + " * joe@truemesh.com\n" + " * {@link here}.\n" + " * me @home\n" + " * geeks @ play\n" + " */"; Lexer lexer = new JFlexLexer(new StringReader(in)); assertLex(Parser.JAVADOCSTART, lexer); assertLex(Parser.JAVADOCLINE, "\n", lexer); assertLex(Parser.JAVADOCLINE, "joe@truemesh.com\n", lexer); assertLex(Parser.JAVADOCLINE, "{@link here}.\n", lexer); assertLex(Parser.JAVADOCLINE, "me @home\n", lexer); assertLex(Parser.JAVADOCLINE, "geeks @ play\n", lexer); assertLex(Parser.JAVADOCEND, lexer); assertLex(0, lexer); } public void testDocCommentContainingStars() throws Exception { String in = "" + "/**\n" + " * 5 * 4\n" + " * SELECT COUNT(*)\n" + " * **stars**everywhere** \n" + " */"; Lexer lexer = new JFlexLexer(new StringReader(in)); assertLex(Parser.JAVADOCSTART, lexer); assertLex(Parser.JAVADOCLINE, "\n", lexer); assertLex(Parser.JAVADOCLINE, "5 * 4\n", lexer); assertLex(Parser.JAVADOCLINE, "SELECT COUNT(*)\n", lexer); assertLex(Parser.JAVADOCLINE, "**stars**everywhere** \n", lexer); assertLex(Parser.JAVADOCEND, lexer); assertLex(0, lexer); } public void testExtraStarsAreIgnoredAtStartAndEnd() throws Exception { String in = "" + "/*****\n" + " * blah\n" + " *****/"; Lexer lexer = new JFlexLexer(new StringReader(in)); assertLex(Parser.JAVADOCSTART, lexer); assertLex(Parser.JAVADOCLINE, "\n", lexer); assertLex(Parser.JAVADOCLINE, "blah\n", lexer); assertLex(Parser.JAVADOCEND, lexer); assertLex(0, lexer); } public void testExtraStarsCompressed() throws Exception { String in = "" + "/***blah***/public"; Lexer lexer = new JFlexLexer(new StringReader(in)); assertLex(Parser.JAVADOCSTART, lexer); assertLex(Parser.JAVADOCLINE, "blah", lexer); assertLex(Parser.JAVADOCEND, lexer); assertLex(Parser.PUBLIC, lexer); assertLex(0, lexer); } public void testIgnoreStarPrefix() throws Exception { String in = "" + "/**\n" + " * simple\n" + "\t * indented\n" + " *nospace\n" + " *** multistar\n" + " *\n" + " */"; Lexer lexer = new JFlexLexer(new StringReader(in)); assertLex(Parser.JAVADOCSTART, lexer); assertLex(Parser.JAVADOCLINE, "\n", lexer); assertLex(Parser.JAVADOCLINE, "simple\n", lexer); assertLex(Parser.JAVADOCLINE, "indented\n", lexer); assertLex(Parser.JAVADOCLINE, "nospace\n", lexer); assertLex(Parser.JAVADOCLINE, "multistar\n", lexer); assertLex(Parser.JAVADOCLINE, "\n", lexer); assertLex(Parser.JAVADOCEND, lexer); assertLex(0, lexer); } // QDOX-200 public void testCompactJavaDocTag() throws Exception { String in = "/** @foo*/"; Lexer lexer = new JFlexLexer(new StringReader(in)); assertLex(Parser.JAVADOCSTART, lexer); assertLex(Parser.JAVADOCTAG, "@foo", lexer); assertLex(Parser.JAVADOCEND, lexer); assertLex(0, lexer); } public void testArrayTokens() throws Exception { String in = "String[] []o[]"; Lexer lexer = new JFlexLexer(new StringReader(in)); assertLex(Parser.IDENTIFIER, "String", lexer); assertLex(Parser.SQUAREOPEN, lexer); assertLex(Parser.SQUARECLOSE, lexer); assertLex(Parser.SQUAREOPEN, lexer); assertLex(Parser.SQUARECLOSE, lexer); assertLex(Parser.IDENTIFIER, "o", lexer); assertLex(Parser.SQUAREOPEN, lexer); assertLex(Parser.SQUARECLOSE, lexer); assertLex(0, lexer); } public void testKeyWords() throws Exception { assertSingleLex("package", Parser.PACKAGE); assertSingleLex("import", Parser.IMPORT); assertSingleLex("public", Parser.PUBLIC); assertSingleLex("protected", Parser.PROTECTED); assertSingleLex("private", Parser.PRIVATE); assertSingleLex("static", Parser.STATIC); assertSingleLex("final", Parser.FINAL); assertSingleLex("abstract", Parser.ABSTRACT); assertSingleLex("native", Parser.NATIVE); assertSingleLex("strictfp", Parser.STRICTFP); assertSingleLex("synchronized", Parser.SYNCHRONIZED); assertSingleLex("transient", Parser.TRANSIENT); assertSingleLex("volatile", Parser.VOLATILE); assertSingleLex("class", Parser.CLASS); assertSingleLex("interface", Parser.INTERFACE); assertSingleLex("throws", Parser.THROWS); assertSingleLex("extends", Parser.EXTENDS); assertSingleLex("implements", Parser.IMPLEMENTS); assertSingleLex("super", Parser.SUPER); } public void testTypeTokens() throws Exception { String in = "Map>"; Lexer lexer = new JFlexLexer(new StringReader(in)); assertLex(Parser.IDENTIFIER, "Map", lexer); assertLex(Parser.LESSTHAN, lexer); assertLex(Parser.QUERY, lexer); assertLex(Parser.EXTENDS, lexer); assertLex(Parser.IDENTIFIER, "A", lexer); assertLex(Parser.AMPERSAND, lexer); assertLex(Parser.IDENTIFIER, "B", lexer); assertLex(Parser.COMMA, lexer); assertLex(Parser.IDENTIFIER, "List", lexer); assertLex(Parser.LESSTHAN, lexer); assertLex(Parser.IDENTIFIER, "String", lexer); assertLex(Parser.GREATERTHAN, lexer); assertLex(Parser.GREATERTHAN, lexer); assertLex(0, lexer); } public void testAnnotationDeclarationTokens() throws Exception { String in = "" + "public @interface Copyright {\n" + " int year();\n" + " String assignee() default \"The CodeHaus\";\n" + "}\n"; Lexer lexer = new JFlexLexer(new StringReader(in)); assertLex(Parser.PUBLIC, lexer); assertLex(Parser.ANNOINTERFACE, lexer); assertLex(Parser.IDENTIFIER, "Copyright", lexer); assertLex(Parser.BRACEOPEN, lexer); assertLex(Parser.IDENTIFIER, "int", lexer); assertLex(Parser.IDENTIFIER, "year", lexer); assertLex(Parser.PARENOPEN, lexer); assertLex(Parser.PARENCLOSE, lexer); assertLex(Parser.SEMI, lexer); assertLex(Parser.IDENTIFIER, "String", lexer); assertLex(Parser.IDENTIFIER, "assignee", lexer); assertLex(Parser.PARENOPEN, lexer); assertLex(Parser.PARENCLOSE, lexer); assertLex(Parser.SEMI, lexer); assertLex(Parser.BRACECLOSE, lexer); assertLex(0, lexer); } public void testAnnotationTokens() throws Exception { String in = "" + "@Copyright (year = 2004, month = \"Jan\")\n" + "@Note(\"Just ignore me\")\n" + "public class LexerTest extends TestCase {}\n"; Lexer lexer = new JFlexLexer(new StringReader(in)); assertLex(Parser.AT, "@", lexer); assertLex(Parser.IDENTIFIER, "Copyright", lexer); assertLex(Parser.PARENOPEN, lexer); assertLex(Parser.IDENTIFIER, "year", lexer); assertLex(Parser.EQUALS, lexer); assertLex(Parser.INTEGER_LITERAL, "2004", lexer); assertLex(Parser.COMMA, lexer); assertLex(Parser.IDENTIFIER, "month", lexer); assertLex(Parser.EQUALS, lexer); assertLex(Parser.STRING_LITERAL, "\"", lexer); // TODO the above should be ... // assertLex(Parser.STRING_LITERAL, "Jan", lexer); assertLex(Parser.PARENCLOSE, lexer); assertLex(Parser.AT, "@", lexer); assertLex(Parser.IDENTIFIER, "Note", lexer); assertLex(Parser.PARENOPEN, lexer); assertLex(Parser.STRING_LITERAL, lexer); assertLex(Parser.PARENCLOSE, lexer); assertLex(Parser.PUBLIC, lexer); assertLex(Parser.CLASS, lexer); assertLex(Parser.IDENTIFIER, "LexerTest", lexer); assertLex(Parser.EXTENDS, lexer); assertLex(Parser.IDENTIFIER, "TestCase", lexer); assertLex(Parser.BRACEOPEN, lexer); assertLex(Parser.BRACECLOSE, lexer); assertLex(0, lexer); } public void testQDOX134_MoreAnnotationTokens() throws Exception { String in = "" + "@myTag name=TestClass attrs=Something1,Something2,Something3\n" + "public class LexerTest extends TestCase {}\n"; Lexer lexer = new JFlexLexer(new StringReader(in)); assertLex(Parser.AT, "@", lexer); assertLex(Parser.IDENTIFIER, "myTag", lexer); assertLex(Parser.IDENTIFIER, "name", lexer); assertLex(Parser.COMMA, lexer); assertLex(Parser.IDENTIFIER, "Something2", lexer); assertLex(Parser.COMMA, lexer); assertLex(Parser.IDENTIFIER, "Something3", lexer); assertLex(Parser.PUBLIC, lexer); assertLex(Parser.CLASS, lexer); assertLex(Parser.IDENTIFIER, "LexerTest", lexer); assertLex(Parser.EXTENDS, lexer); assertLex(Parser.IDENTIFIER, "TestCase", lexer); assertLex(Parser.BRACEOPEN, lexer); assertLex(Parser.BRACECLOSE, lexer); assertLex(0, lexer); } public void testEnumConstructor() throws Exception { String in = "enum Foo { a(\"hello\"); int someField; }"; Lexer lexer = new JFlexLexer(new StringReader(in)); assertLex(Parser.ENUM, lexer); assertLex(Parser.IDENTIFIER, lexer); assertLex(Parser.BRACEOPEN, lexer); assertLex(Parser.IDENTIFIER, lexer); assertLex(Parser.PARENBLOCK, lexer); assertLex(Parser.SEMI, lexer); assertLex(Parser.IDENTIFIER, lexer); assertLex(Parser.IDENTIFIER, lexer); assertLex(Parser.SEMI, lexer); assertLex(Parser.BRACECLOSE, lexer); } public void testEnumWithMethods() throws Exception { String in = "" + "enum Animal {" + " DUCK { public void speak() { System.out.println(\"quack!\"); } }" + "}"; Lexer lexer = new JFlexLexer(new StringReader(in)); assertLex(Parser.ENUM, lexer); assertLex(Parser.IDENTIFIER, lexer); assertLex(Parser.BRACEOPEN, lexer); assertLex(Parser.IDENTIFIER, lexer); assertLex(Parser.CODEBLOCK, lexer); assertLex(Parser.BRACECLOSE, lexer); } private void assertSingleLex(String in, short expectedLex) throws Exception { Lexer lexer = new JFlexLexer(new StringReader(in)); assertLex(expectedLex, lexer); assertLex(0, lexer); } private void assertLex(int expectedToken, Lexer lexer) throws IOException { Object expected = tokens.get(new Integer(expectedToken)); Object actual = tokens.get(new Integer(lexer.lex())); assertEquals(expected, actual); } private void assertLex(int expectedToken, String expectedText, Lexer lexer) throws IOException { assertLex(expectedToken, lexer); assertEquals(expectedText, lexer.text()); } // for QDOX-140 public void testNonAsciiMethodNameDoesNotCrashLexerButChewsUpUnicodeEscapedSequencesBadly() throws Exception { String in = "" + "interface X { " + " void paramWithNonAsciis\\u00E4\\u00F6\\u00FC\\u00DF();" + "} "; Lexer lexer = new JFlexLexer(new StringReader(in)); assertLex(Parser.INTERFACE, lexer); assertLex(Parser.IDENTIFIER, lexer); assertLex(Parser.BRACEOPEN, lexer); assertLex(Parser.IDENTIFIER, "void", lexer); assertLex(Parser.IDENTIFIER, "paramWithNonAsciis\\u00E4\\u00F6\\u00FC\\u00DF", lexer); assertLex(Parser.PARENOPEN, lexer); assertLex(Parser.PARENCLOSE, lexer); assertLex(Parser.SEMI, lexer); assertLex(Parser.BRACECLOSE, lexer); assertLex(0, lexer); } //for QDOX-158 public void testAnnotationWithMultipleParameters() throws Exception { String in = "@MyFunction.MyInterface( prefix1 = \"abc\", prefix2 = \"abc\" )"; Lexer lexer = new JFlexLexer(new StringReader(in)); assertLex(Parser.AT, lexer); assertLex(Parser.IDENTIFIER, lexer); assertLex(Parser.DOT, lexer); assertLex(Parser.IDENTIFIER, lexer); assertLex(Parser.PARENOPEN, lexer); assertLex(Parser.IDENTIFIER, lexer); assertLex(Parser.EQUALS, lexer); assertLex(Parser.STRING_LITERAL, lexer); assertLex(Parser.COMMA, lexer); assertLex(Parser.IDENTIFIER, lexer); assertLex(Parser.EQUALS, lexer); assertLex(Parser.STRING_LITERAL, lexer); assertLex(Parser.PARENCLOSE, lexer); } public void testSimpleAnnotation() throws Exception { String in = "@Override\n public boolean isReadOnly(final ELContext context)"; Lexer lexer = new JFlexLexer(new StringReader(in)); assertLex(Parser.AT, lexer); assertLex(Parser.IDENTIFIER, lexer); assertLex(Parser.PUBLIC, lexer); assertLex(Parser.IDENTIFIER, lexer); assertLex(Parser.IDENTIFIER, lexer); assertLex(Parser.PARENOPEN, lexer); assertLex(Parser.FINAL, lexer); assertLex(Parser.IDENTIFIER, lexer); assertLex(Parser.IDENTIFIER, lexer); assertLex(Parser.PARENCLOSE, lexer); } public void testMultipleRowAnnotation() throws Exception { String in = "@JSFComponent\n (name = \"h:inputHidden\")"; Lexer lexer = new JFlexLexer(new StringReader(in)); assertLex(Parser.AT, lexer); assertLex(Parser.IDENTIFIER, lexer); assertLex(Parser.PARENOPEN, lexer); assertLex(Parser.IDENTIFIER, lexer); assertLex(Parser.EQUALS, lexer); assertLex(Parser.STRING_LITERAL, lexer); assertLex(Parser.PARENCLOSE, lexer); } public void testEnumWithAnnotations() throws Exception { String in = "class Foo {\n" + "public enum BasicType {\n" + "@XmlEnumValue(\"text\")\n" + "VALUE(\"value\"); }\n" + "}"; Lexer lexer = new JFlexLexer(new StringReader(in)); assertLex(Parser.CLASS, lexer); assertLex(Parser.IDENTIFIER, lexer); assertLex(Parser.BRACEOPEN, lexer); assertLex(Parser.PUBLIC, lexer); assertLex(Parser.ENUM, lexer); assertLex(Parser.IDENTIFIER, lexer); assertLex(Parser.BRACEOPEN, lexer); assertLex(Parser.AT, lexer); assertLex(Parser.IDENTIFIER, lexer); assertLex(Parser.PARENOPEN, lexer); assertLex(Parser.STRING_LITERAL, lexer); assertLex(Parser.PARENCLOSE, lexer); assertLex(Parser.IDENTIFIER, lexer); assertLex(Parser.PARENBLOCK, lexer); assertLex(Parser.SEMI, lexer); } } qdox-qdox-1.12.1/src/test/com/thoughtworks/qdox/parser/MockBuilder.java000066400000000000000000000166771204551233600261500ustar00rootroot00000000000000package com.thoughtworks.qdox.parser; import org.jmock.expectation.ExpectationCounter; import org.jmock.expectation.ExpectationList; import com.thoughtworks.qdox.model.Annotation; import com.thoughtworks.qdox.model.Type; import com.thoughtworks.qdox.parser.structs.ClassDef; import com.thoughtworks.qdox.parser.structs.FieldDef; import com.thoughtworks.qdox.parser.structs.MethodDef; import com.thoughtworks.qdox.parser.structs.PackageDef; import com.thoughtworks.qdox.parser.structs.TagDef; import com.thoughtworks.qdox.parser.structs.TypeDef; class MockBuilder implements Builder { private ExpectationCounter myAddPackageCalls = new ExpectationCounter("com.thoughtworks.qdox.parser.Builder AddPackageCalls"); private ExpectationList myAddPackageParameter0Values = new ExpectationList("com.thoughtworks.qdox.parser.Builder.addPackage() : java.lang.String packageName"); private ExpectationCounter myAddImportCalls = new ExpectationCounter("com.thoughtworks.qdox.parser.Builder AddImportCalls"); private ExpectationList myAddImportParameter0Values = new ExpectationList("com.thoughtworks.qdox.parser.Builder.addImport() : java.lang.String importName"); private ExpectationCounter myAddJavaDocCalls = new ExpectationCounter("com.thoughtworks.qdox.parser.Builder AddJavaDocCalls"); private ExpectationList myAddJavaDocParameter0Values = new ExpectationList("com.thoughtworks.qdox.parser.Builder.addJavaDoc() : java.lang.String text"); private ExpectationCounter myAddJavaDocTagCalls = new ExpectationCounter("com.thoughtworks.qdox.parser.Builder AddJavaDocTagCalls"); private ExpectationList myAddJavaDocTagParameter0Values = new ExpectationList("com.thoughtworks.qdox.parser.Builder.addJavaDocTag() : java.lang.String tag"); private ExpectationList myAddJavaDocTagParameter1Values = new ExpectationList("com.thoughtworks.qdox.parser.Builder.addJavaDocTag() : java.lang.String text"); private ExpectationCounter myBeginClassCalls = new ExpectationCounter("com.thoughtworks.qdox.parser.Builder BeginClassCalls"); private ExpectationList myBeginClassParameter0Values = new ExpectationList("com.thoughtworks.qdox.parser.Builder.beginClass() : com.thoughtworks.qdox.parser.structs.ClassDef def"); private ExpectationCounter myEndClassCalls = new ExpectationCounter("com.thoughtworks.qdox.parser.Builder EndClassCalls"); private ExpectationCounter myBeginMethodCalls = new ExpectationCounter("com.thoughtworks.qdox.parser.Builder BeginMethodCalls"); private ExpectationCounter myEndMethodCalls = new ExpectationCounter("com.thoughtworks.qdox.parser.Builder EndMethodCalls"); private ExpectationList myEndMethodParameter0Values = new ExpectationList("com.thoughtworks.qdox.parser.Builder.endMethod() : com.thoughtworks.qdox.parser.structs.MethodDef def"); private ExpectationCounter myAddFieldCalls = new ExpectationCounter("com.thoughtworks.qdox.parser.Builder AddFieldCalls"); private ExpectationList myAddFieldParameter0Values = new ExpectationList("com.thoughtworks.qdox.parser.Builder.addField() : com.thoughtworks.qdox.parser.structs.FieldDef def"); private ExpectationCounter myAddParameterCalls = new ExpectationCounter("com.thoughtworks.qdox.parser.Builder AddParameterCalls"); private ExpectationList myAddParameter0Values = new ExpectationList("com.thoughtworks.qdox.parser.Builder.addParameter() : com.thoughtworks.qdox.parser.structs.FieldDef def"); public void setExpectedAddPackageCalls(int calls) { myAddPackageCalls.setExpected(calls); } public void addExpectedAddPackageValues(PackageDef arg0) { myAddPackageParameter0Values.addExpected(arg0); } public void addPackage(PackageDef arg0) { myAddPackageCalls.inc(); myAddPackageParameter0Values.addActual(arg0); } public void setExpectedAddImportCalls(int calls) { myAddImportCalls.setExpected(calls); } public void addExpectedAddImportValues(String arg0) { myAddImportParameter0Values.addExpected(arg0); } public void addImport(String arg0) { myAddImportCalls.inc(); myAddImportParameter0Values.addActual(arg0); } public void setExpectedAddJavaDocCalls(int calls) { myAddJavaDocCalls.setExpected(calls); } public void addExpectedAddJavaDocValues(String arg0) { myAddJavaDocParameter0Values.addExpected(arg0); } public void addJavaDoc(String arg0) { myAddJavaDocCalls.inc(); myAddJavaDocParameter0Values.addActual(arg0); } public void setExpectedAddJavaDocTagCalls(int calls) { myAddJavaDocTagCalls.setExpected(calls); } public void addExpectedAddJavaDocTagValues(TagDef arg0) { myAddJavaDocTagParameter0Values.addExpected(arg0); } public void addJavaDocTag(TagDef arg0) { myAddJavaDocTagCalls.inc(); myAddJavaDocTagParameter0Values.addActual(arg0); } public void setExpectedBeginClassCalls(int calls) { myBeginClassCalls.setExpected(calls); } public void addExpectedBeginClassValues(ClassDef arg0) { myBeginClassParameter0Values.addExpected(arg0); } public void beginClass(ClassDef arg0) { myBeginClassCalls.inc(); myBeginClassParameter0Values.addActual(arg0); } public void setExpectedEndClassCalls(int calls) { myEndClassCalls.setExpected(calls); } public void endClass() { myEndClassCalls.inc(); } public void beginMethod() { myBeginMethodCalls.inc(); } public void setExpectedEndMethodCalls(int calls) { myEndMethodCalls.setExpected(calls); } public void addExpectedAddMethodValues(MethodDef arg0) { myEndMethodParameter0Values.addExpected(arg0); } public void endMethod(MethodDef arg0) { myEndMethodCalls.inc(); myEndMethodParameter0Values.addActual(arg0); } public void setExpectedAddFieldCalls(int calls) { myAddFieldCalls.setExpected(calls); } public void addExpectedAddFieldValues(FieldDef arg0) { myAddFieldParameter0Values.addExpected(arg0); } public void addField(FieldDef arg0) { myAddFieldCalls.inc(); myAddFieldParameter0Values.addActual(arg0); } public void addAnnotation( Annotation annotation ) { // Empty } public void verify() { myAddPackageCalls.verify(); myAddPackageParameter0Values.verify(); myAddImportCalls.verify(); myAddImportParameter0Values.verify(); myAddJavaDocCalls.verify(); myAddJavaDocParameter0Values.verify(); myAddJavaDocTagCalls.verify(); myAddJavaDocTagParameter0Values.verify(); myAddJavaDocTagParameter1Values.verify(); myBeginClassCalls.verify(); myBeginClassParameter0Values.verify(); myEndClassCalls.verify(); myBeginMethodCalls.verify(); myEndMethodCalls.verify(); myEndMethodParameter0Values.verify(); myAddFieldCalls.verify(); myAddFieldParameter0Values.verify(); } public Type createType( String name, int dimensions ) { return null; } public Type createType(TypeDef name) { return null; } public void setExpectedAddParameterCalls(int calls) { myAddParameterCalls.setExpected(calls); } public void addExpectedAddParameterValues(FieldDef arg0) { myAddParameter0Values.addExpected(arg0); } public void addParameter(FieldDef arg0) { myAddParameterCalls.inc(); myAddParameter0Values.addActual(arg0); } } qdox-qdox-1.12.1/src/test/com/thoughtworks/qdox/parser/MockLexer.java000066400000000000000000000014461204551233600256250ustar00rootroot00000000000000package com.thoughtworks.qdox.parser; import org.jmock.expectation.ReturnObjectList; class MockLexer implements Lexer { private ReturnObjectList textReturn = new ReturnObjectList("text"); private ReturnObjectList lexReturn = new ReturnObjectList("lex"); public void setupText(String value) { textReturn.addObjectToReturn(value); } public void setupLex(int value) { lexReturn.addObjectToReturn(value); } public int lex() { return ((Integer) lexReturn.nextReturnObject()).intValue(); } public String text() { return (String) textReturn.nextReturnObject(); } public int getLine() { return -1; } public int getColumn() { return -1; } public String getCodeBody() { return ""; } } qdox-qdox-1.12.1/src/test/com/thoughtworks/qdox/parser/ParserTest.java000066400000000000000000002155031204551233600260310ustar00rootroot00000000000000package com.thoughtworks.qdox.parser; import java.util.ArrayList; import junit.framework.TestCase; import com.thoughtworks.qdox.parser.impl.Parser; import com.thoughtworks.qdox.parser.structs.FieldDef; import com.thoughtworks.qdox.parser.structs.ClassDef; import com.thoughtworks.qdox.parser.structs.MethodDef; import com.thoughtworks.qdox.parser.structs.PackageDef; import com.thoughtworks.qdox.parser.structs.TagDef; import com.thoughtworks.qdox.parser.structs.TypeDef; import com.thoughtworks.qdox.parser.structs.WildcardTypeDef; public class ParserTest extends TestCase { private MockLexer lexer; private MockBuilder builder; public ParserTest(String s) { super(s); } protected void setUp() throws Exception { super.setUp(); lexer = new MockLexer(); builder = new MockBuilder(); } public void testPackageWithOneWord() throws Exception { // setup values setupLex(Parser.PACKAGE); setupLex(Parser.IDENTIFIER, "mypackage"); setupLex(Parser.SEMI); setupLex(0); // expectations builder.addExpectedAddPackageValues(new PackageDef("mypackage")); // execute Parser parser = new Parser(lexer, builder); parser.parse(); // verify builder.verify(); } public void testPackageWithMultipleWords() throws Exception { // setup values setupLex(Parser.PACKAGE); setupLex(Parser.IDENTIFIER, "com"); setupLex(Parser.DOT); setupLex(Parser.IDENTIFIER, "blah"); setupLex(Parser.DOT); setupLex(Parser.IDENTIFIER, "thingy"); setupLex(Parser.DOT); setupLex(Parser.IDENTIFIER, "x"); setupLex(Parser.SEMI); setupLex(0); // expectations builder.addExpectedAddPackageValues(new PackageDef("com.blah.thingy.x")); // execute Parser parser = new Parser(lexer, builder); parser.parse(); // verify builder.verify(); } public void testImportWithOneWord() throws Exception { // setup values setupLex(Parser.IMPORT); setupLex(Parser.IDENTIFIER, "mypackage"); setupLex(Parser.SEMI); setupLex(0); // expectations builder.addExpectedAddImportValues("mypackage"); // execute Parser parser = new Parser(lexer, builder); parser.parse(); // verify builder.verify(); } public void testImportWithMultipleWords() throws Exception { // setup values setupLex(Parser.IMPORT); setupLex(Parser.IDENTIFIER, "com"); setupLex(Parser.DOT); setupLex(Parser.IDENTIFIER, "blah"); setupLex(Parser.DOT); setupLex(Parser.IDENTIFIER, "thingy"); setupLex(Parser.DOT); setupLex(Parser.IDENTIFIER, "x"); setupLex(Parser.SEMI); setupLex(0); // expectations builder.addExpectedAddImportValues("com.blah.thingy.x"); // execute Parser parser = new Parser(lexer, builder); parser.parse(); // verify builder.verify(); } public void testImportWithOneWordAndStar() throws Exception { // setup values setupLex(Parser.IMPORT); setupLex(Parser.IDENTIFIER, "mypackage"); setupLex(Parser.DOT); setupLex(Parser.STAR); setupLex(Parser.SEMI); setupLex(0); // expectations builder.addExpectedAddImportValues("mypackage.*"); // execute Parser parser = new Parser(lexer, builder); parser.parse(); // verify builder.verify(); } public void testImportWithMultipleWordsAndStar() throws Exception { // setup values setupLex(Parser.IMPORT); setupLex(Parser.IDENTIFIER, "com"); setupLex(Parser.DOT); setupLex(Parser.IDENTIFIER, "blah"); setupLex(Parser.DOT); setupLex(Parser.IDENTIFIER, "thingy"); setupLex(Parser.DOT); setupLex(Parser.STAR); setupLex(Parser.SEMI); setupLex(0); // expectations builder.addExpectedAddImportValues("com.blah.thingy.*"); // execute Parser parser = new Parser(lexer, builder); parser.parse(); // verify builder.verify(); } public void testImportStaticWithOneWord() throws Exception { // setup values setupLex( Parser.IMPORT ); setupLex( Parser.STATIC ); setupLex( Parser.IDENTIFIER, "mypackage" ); setupLex( Parser.SEMI ); setupLex( 0 ); // expectations builder.addExpectedAddImportValues( "static mypackage" ); // execute Parser parser = new Parser( lexer, builder ); parser.parse(); // verify builder.verify(); } public void testImportStaticWithMultipleWords() throws Exception { // setup values setupLex( Parser.IMPORT ); setupLex( Parser.STATIC ); setupLex( Parser.IDENTIFIER, "com" ); setupLex( Parser.DOT ); setupLex( Parser.IDENTIFIER, "blah" ); setupLex( Parser.DOT ); setupLex( Parser.IDENTIFIER, "Thingy" ); setupLex( Parser.DOT ); setupLex( Parser.IDENTIFIER, "x" ); setupLex( Parser.SEMI ); setupLex( 0 ); // expectations builder.addExpectedAddImportValues( "static com.blah.Thingy.x" ); // execute Parser parser = new Parser( lexer, builder ); parser.parse(); // verify builder.verify(); } public void testImportStaticWithOneWordAndStar() throws Exception { // setup values setupLex( Parser.IMPORT ); setupLex( Parser.STATIC ); setupLex( Parser.IDENTIFIER, "MyClass" ); setupLex( Parser.DOT ); setupLex( Parser.STAR ); setupLex( Parser.SEMI ); setupLex( 0 ); // expectations builder.addExpectedAddImportValues( "static MyClass.*" ); // execute Parser parser = new Parser( lexer, builder ); parser.parse(); // verify builder.verify(); } public void testImportStaticWithMultipleWordsAndStar() throws Exception { // setup values setupLex( Parser.IMPORT ); setupLex( Parser.STATIC ); setupLex( Parser.IDENTIFIER, "com" ); setupLex( Parser.DOT ); setupLex( Parser.IDENTIFIER, "blah" ); setupLex( Parser.DOT ); setupLex( Parser.IDENTIFIER, "Thingy" ); setupLex( Parser.DOT ); setupLex( Parser.STAR ); setupLex( Parser.SEMI ); setupLex( 0 ); // expectations builder.addExpectedAddImportValues( "static com.blah.Thingy.*" ); // execute Parser parser = new Parser( lexer, builder ); parser.parse(); // verify builder.verify(); } public void testOneLineJavaDoc() throws Exception { // setup values setupLex(Parser.JAVADOCSTART); setupLex(Parser.JAVADOCLINE, "This is great!"); setupLex(Parser.JAVADOCEND); setupLex(0); // expectations builder.addExpectedAddJavaDocValues("This is great!"); // execute Parser parser = new Parser(lexer, builder); parser.parse(); // verify builder.verify(); } public void testOneJavaDocTag() throws Exception { // setup values setupLex(Parser.JAVADOCSTART); setupLex(Parser.JAVADOCTAG, "@This"); setupLex(Parser.JAVADOCLINE, "is great!"); setupLex(Parser.JAVADOCEND); setupLex(0); // expectations builder.addExpectedAddJavaDocTagValues(new TagDef("This", "is great!")); // execute Parser parser = new Parser(lexer, builder); parser.parse(); // verify builder.verify(); } public void testOneJavaDocTagWithNoValue() throws Exception { // setup values setupLex(Parser.JAVADOCSTART); setupLex(Parser.JAVADOCTAG, "@eatme"); setupLex(Parser.JAVADOCEND); setupLex(0); // expectations builder.addExpectedAddJavaDocTagValues(new TagDef("eatme", "")); // execute Parser parser = new Parser(lexer, builder); parser.parse(); // verify builder.verify(); } public void testOneMultiLineJavaDocTag() throws Exception { // setup values setupLex(Parser.JAVADOCSTART); setupLex(Parser.JAVADOCTAG, "@This"); setupLex(Parser.JAVADOCLINE, "is great! Mmmkay."); setupLex(Parser.JAVADOCEND); setupLex(0); // expectations builder.addExpectedAddJavaDocValues(""); builder.addExpectedAddJavaDocTagValues( new TagDef("This", "is great! Mmmkay.") ); // execute Parser parser = new Parser(lexer, builder); parser.parse(); // verify builder.verify(); } public void testMultipleJavaDocTags() throws Exception { // setup values setupLex(Parser.JAVADOCSTART); setupLex(Parser.JAVADOCTAG, "@This"); setupLex(Parser.JAVADOCLINE, "is great!"); setupLex(Parser.JAVADOCTAG, "@mock"); setupLex(Parser.JAVADOCLINE, "generate"); setupLex(Parser.JAVADOCEND); setupLex(0); // expectations builder.addExpectedAddJavaDocValues(""); builder.addExpectedAddJavaDocTagValues(new TagDef("This", "is great!")); builder.addExpectedAddJavaDocTagValues(new TagDef("mock", "generate")); // execute Parser parser = new Parser(lexer, builder); parser.parse(); // verify builder.verify(); } public void testJavaDocTextAndMultipleJavaDocTags() throws Exception { // setup values setupLex(Parser.JAVADOCSTART); setupLex(Parser.JAVADOCLINE, "Welcome! Here is my class."); setupLex(Parser.JAVADOCTAG, "@This"); setupLex(Parser.JAVADOCLINE, "is great!"); setupLex(Parser.JAVADOCTAG, "@mock"); setupLex(Parser.JAVADOCLINE, "generate"); setupLex(Parser.JAVADOCEND); setupLex(0); // expectations builder.addExpectedAddJavaDocValues("Welcome! Here is my class."); builder.addExpectedAddJavaDocTagValues(new TagDef("This", "is great!")); builder.addExpectedAddJavaDocTagValues(new TagDef("mock", "generate")); // execute Parser parser = new Parser(lexer, builder); parser.parse(); // verify builder.verify(); } public void testJavaDocEmpty() throws Exception { // setup values setupLex(Parser.JAVADOCSTART); setupLex(Parser.JAVADOCEND); setupLex(0); // expectations builder.addExpectedAddJavaDocValues(""); builder.setExpectedAddJavaDocTagCalls(0); // execute Parser parser = new Parser(lexer, builder); parser.parse(); // verify builder.verify(); } public void testJavaDocOnlyContainsNewLines() throws Exception { // setup values setupLex(Parser.JAVADOCSTART); setupLex(Parser.JAVADOCEND); setupLex(0); // expectations builder.addExpectedAddJavaDocValues(""); builder.setExpectedAddJavaDocTagCalls(0); // execute Parser parser = new Parser(lexer, builder); parser.parse(); // verify builder.verify(); } public void testEmptyVanillaClass() throws Exception { // setup values setupLex(Parser.CLASS); setupLex(Parser.IDENTIFIER, "MyClass"); setupLex(Parser.BRACEOPEN); setupLex(Parser.BRACECLOSE); setupLex(0); // expectations ClassDef cls = new ClassDef(); cls.name = "MyClass"; builder.addExpectedBeginClassValues(cls); // execute Parser parser = new Parser(lexer, builder); parser.parse(); // verify builder.verify(); } public void testEmptyVanillaInterface() throws Exception { // setup values setupLex(Parser.INTERFACE); setupLex(Parser.IDENTIFIER, "MyInterface"); setupLex(Parser.BRACEOPEN); setupLex(Parser.BRACECLOSE); setupLex(0); // expectations ClassDef cls = new ClassDef(); cls.name = "MyInterface"; cls.type = ClassDef.INTERFACE; builder.addExpectedBeginClassValues(cls); // execute Parser parser = new Parser(lexer, builder); parser.parse(); // verify builder.verify(); } public void testEmptyVanillaEnum() throws Exception { // setup values setupLex(Parser.ENUM); setupLex(Parser.IDENTIFIER, "MyEnum"); setupLex(Parser.BRACEOPEN); setupLex(Parser.BRACECLOSE); setupLex(0); // expectations ClassDef cls = new ClassDef(); cls.name = "MyEnum"; cls.type = ClassDef.ENUM; builder.addExpectedBeginClassValues(cls); // execute Parser parser = new Parser(lexer, builder); parser.parse(); // verify builder.verify(); } public void testEmptyClassExtendsAnotherClass() throws Exception { // setup values setupLex(Parser.CLASS); setupLex(Parser.IDENTIFIER, "MySubClass"); setupLex(Parser.EXTENDS); setupLex(Parser.IDENTIFIER, "com"); setupLex(Parser.DOT); setupLex(Parser.IDENTIFIER, "blah"); setupLex(Parser.DOT); setupLex(Parser.IDENTIFIER, "MyBaseClass"); setupLex(Parser.BRACEOPEN); setupLex(Parser.BRACECLOSE); setupLex(0); // expectations ClassDef cls = new ClassDef(); cls.name = "MySubClass"; cls.extendz.add(new TypeDef("com.blah.MyBaseClass")); builder.addExpectedBeginClassValues(cls); // execute Parser parser = new Parser(lexer, builder); parser.parse(); // verify builder.verify(); } public void testEmptyInterfaceExtendsMultipleInterfaces() throws Exception { // setup values setupLex(Parser.INTERFACE); setupLex(Parser.IDENTIFIER, "MyInterface"); setupLex(Parser.EXTENDS); setupLex(Parser.IDENTIFIER, "com"); setupLex(Parser.DOT); setupLex(Parser.IDENTIFIER, "blah"); setupLex(Parser.DOT); setupLex(Parser.IDENTIFIER, "AnotherInterface"); setupLex(Parser.COMMA); setupLex(Parser.IDENTIFIER, "Serializable"); setupLex(Parser.BRACEOPEN); setupLex(Parser.BRACECLOSE); setupLex(0); // expectations ClassDef cls = new ClassDef(); cls.name = "MyInterface"; cls.type = ClassDef.INTERFACE; cls.extendz.add(new TypeDef("com.blah.AnotherInterface")); cls.extendz.add(new TypeDef("Serializable")); builder.addExpectedBeginClassValues(cls); // execute Parser parser = new Parser(lexer, builder); parser.parse(); // verify builder.verify(); } public void testEmptyClassImplementsOneInterface() throws Exception { // setup values setupLex(Parser.CLASS); setupLex(Parser.IDENTIFIER, "MyClass"); setupLex(Parser.IMPLEMENTS); setupLex(Parser.IDENTIFIER, "com"); setupLex(Parser.DOT); setupLex(Parser.IDENTIFIER, "blah"); setupLex(Parser.DOT); setupLex(Parser.IDENTIFIER, "AnInterface"); setupLex(Parser.BRACEOPEN); setupLex(Parser.BRACECLOSE); setupLex(0); // expectations ClassDef cls = new ClassDef(); cls.name = "MyClass"; cls.implementz.add(new TypeDef("com.blah.AnInterface")); builder.addExpectedBeginClassValues(cls); // execute Parser parser = new Parser(lexer, builder); parser.parse(); // verify builder.verify(); } public void testEmptyClassImplementsMultipleInterfaces() throws Exception { // setup values setupLex(Parser.CLASS); setupLex(Parser.IDENTIFIER, "MyClass"); setupLex(Parser.IMPLEMENTS); setupLex(Parser.IDENTIFIER, "com"); setupLex(Parser.DOT); setupLex(Parser.IDENTIFIER, "blah"); setupLex(Parser.DOT); setupLex(Parser.IDENTIFIER, "AnInterface"); setupLex(Parser.COMMA); setupLex(Parser.IDENTIFIER, "java"); setupLex(Parser.DOT); setupLex(Parser.IDENTIFIER, "io"); setupLex(Parser.DOT); setupLex(Parser.IDENTIFIER, "Serializable"); setupLex(Parser.COMMA); setupLex(Parser.IDENTIFIER, "Eatable"); setupLex(Parser.BRACEOPEN); setupLex(Parser.BRACECLOSE); setupLex(0); // expectations ClassDef cls = new ClassDef(); cls.name = "MyClass"; cls.implementz.add(new TypeDef("com.blah.AnInterface")); cls.implementz.add(new TypeDef("java.io.Serializable")); cls.implementz.add(new TypeDef("Eatable")); builder.addExpectedBeginClassValues(cls); // execute Parser parser = new Parser(lexer, builder); parser.parse(); // verify builder.verify(); } public void testEmptyClassExtendsOneClassAndImplementsOneInterface() throws Exception { // setup values setupLex(Parser.CLASS); setupLex(Parser.IDENTIFIER, "MyClass"); setupLex(Parser.EXTENDS); setupLex(Parser.IDENTIFIER, "mypackage"); setupLex(Parser.DOT); setupLex(Parser.IDENTIFIER, "BaseClass"); setupLex(Parser.IMPLEMENTS); setupLex(Parser.IDENTIFIER, "com"); setupLex(Parser.DOT); setupLex(Parser.IDENTIFIER, "blah"); setupLex(Parser.DOT); setupLex(Parser.IDENTIFIER, "AnInterface"); setupLex(Parser.BRACEOPEN); setupLex(Parser.BRACECLOSE); setupLex(0); // expectations ClassDef cls = new ClassDef(); cls.name = "MyClass"; cls.extendz.add(new TypeDef("mypackage.BaseClass")); cls.implementz.add(new TypeDef("com.blah.AnInterface")); builder.addExpectedBeginClassValues(cls); // execute Parser parser = new Parser(lexer, builder); parser.parse(); // verify builder.verify(); } public void testEmptyClassExtendsOneClassAndImplementsMultipleInterface() throws Exception { // setup values setupLex(Parser.CLASS); setupLex(Parser.IDENTIFIER, "MyClass"); setupLex(Parser.EXTENDS); setupLex(Parser.IDENTIFIER, "mypackage"); setupLex(Parser.DOT); setupLex(Parser.IDENTIFIER, "BaseClass"); setupLex(Parser.IMPLEMENTS); setupLex(Parser.IDENTIFIER, "com"); setupLex(Parser.DOT); setupLex(Parser.IDENTIFIER, "blah"); setupLex(Parser.DOT); setupLex(Parser.IDENTIFIER, "AnInterface"); setupLex(Parser.COMMA); setupLex(Parser.IDENTIFIER, "java"); setupLex(Parser.DOT); setupLex(Parser.IDENTIFIER, "io"); setupLex(Parser.DOT); setupLex(Parser.IDENTIFIER, "Serializable"); setupLex(Parser.COMMA); setupLex(Parser.IDENTIFIER, "Eatable"); setupLex(Parser.BRACEOPEN); setupLex(Parser.BRACECLOSE); setupLex(0); // expectations ClassDef cls = new ClassDef(); cls.name = "MyClass"; cls.extendz.add(new TypeDef("mypackage.BaseClass")); cls.implementz.add(new TypeDef("com.blah.AnInterface")); cls.implementz.add(new TypeDef("java.io.Serializable")); cls.implementz.add(new TypeDef("Eatable")); builder.addExpectedBeginClassValues(cls); // execute Parser parser = new Parser(lexer, builder); parser.parse(); // verify builder.verify(); } public void testEmptyClassWithPublicFinalModifiers() throws Exception { // setup values setupLex(Parser.PUBLIC); setupLex(Parser.FINAL); setupLex(Parser.CLASS); setupLex(Parser.IDENTIFIER, "MyClass"); setupLex(Parser.BRACEOPEN); setupLex(Parser.BRACECLOSE); setupLex(0); // expectations ClassDef cls = new ClassDef(); cls.name = "MyClass"; cls.modifiers.add("public"); cls.modifiers.add("final"); builder.addExpectedBeginClassValues(cls); // execute Parser parser = new Parser(lexer, builder); parser.parse(); // verify builder.verify(); } public void testEmptyClassWithAllModifiers() throws Exception { // setup values setupLex(Parser.PUBLIC); setupLex(Parser.PROTECTED); setupLex(Parser.PRIVATE); setupLex(Parser.FINAL); setupLex(Parser.ABSTRACT); setupLex(Parser.CLASS); setupLex(Parser.IDENTIFIER, "MyClass"); setupLex(Parser.BRACEOPEN); setupLex(Parser.BRACECLOSE); setupLex(0); // expectations ClassDef cls = new ClassDef(); cls.name = "MyClass"; cls.modifiers.add("public"); cls.modifiers.add("protected"); cls.modifiers.add("private"); cls.modifiers.add("final"); cls.modifiers.add("abstract"); builder.addExpectedBeginClassValues(cls); // execute Parser parser = new Parser(lexer, builder); parser.parse(); // verify builder.verify(); } public void testMultipleClassesInSingleFile() throws Exception { // setup values setupLex(Parser.CLASS); setupLex(Parser.IDENTIFIER, "Class1"); setupLex(Parser.BRACEOPEN); setupLex(Parser.BRACECLOSE); setupLex(Parser.PUBLIC); setupLex(Parser.CLASS); setupLex(Parser.IDENTIFIER, "Class2"); setupLex(Parser.EXTENDS); setupLex(Parser.IDENTIFIER, "SubClass"); setupLex(Parser.BRACEOPEN); setupLex(Parser.BRACECLOSE); setupLex(Parser.INTERFACE); setupLex(Parser.IDENTIFIER, "Intf1"); setupLex(Parser.BRACEOPEN); setupLex(Parser.BRACECLOSE); setupLex(0); // expectations ClassDef cls1 = new ClassDef(); cls1.name = "Class1"; cls1.type = ClassDef.CLASS; builder.addExpectedBeginClassValues(cls1); ClassDef cls2 = new ClassDef(); cls2.name = "Class2"; cls2.type = ClassDef.CLASS; cls2.modifiers.add("public"); cls2.extendz.add(new TypeDef("SubClass")); builder.addExpectedBeginClassValues(cls2); ClassDef cls3 = new ClassDef(); cls3.name = "Intf1"; cls3.type = ClassDef.INTERFACE; builder.addExpectedBeginClassValues(cls3); // execute Parser parser = new Parser(lexer, builder); parser.parse(); // verify builder.verify(); } public void testSemiColonBetweenClass() throws Exception { // setup values setupLex(Parser.CLASS); setupLex(Parser.IDENTIFIER, "Class1"); setupLex(Parser.BRACEOPEN); setupLex(Parser.BRACECLOSE); setupLex(Parser.SEMI); // ; setupLex(Parser.CLASS); setupLex(Parser.IDENTIFIER, "Class2"); setupLex(Parser.BRACEOPEN); setupLex(Parser.BRACECLOSE); setupLex(Parser.SEMI); // ; setupLex(0); // expectations ClassDef cls1 = new ClassDef(); cls1.name = "Class1"; cls1.type = ClassDef.CLASS; builder.addExpectedBeginClassValues(cls1); ClassDef cls2 = new ClassDef(); cls2.name = "Class2"; cls2.type = ClassDef.CLASS; builder.addExpectedBeginClassValues(cls2); // execute Parser parser = new Parser(lexer, builder); parser.parse(); // verify builder.verify(); } public void testJavaDocAppearingAllOverThePlace() throws Exception { // setup values setupLex(Parser.JAVADOCSTART); setupLex(Parser.JAVADOCLINE, "javadoc1"); setupLex(Parser.JAVADOCEND); setupLex(Parser.JAVADOCSTART); setupLex(Parser.JAVADOCLINE, "javadoc2"); setupLex(Parser.JAVADOCEND); setupLex(Parser.PACKAGE); setupLex(Parser.IDENTIFIER, "mypackage"); setupLex(Parser.SEMI); setupLex(Parser.JAVADOCSTART); setupLex(Parser.JAVADOCLINE, "javadoc3"); setupLex(Parser.JAVADOCEND); setupLex(Parser.JAVADOCSTART); setupLex(Parser.JAVADOCLINE, "javadoc4"); setupLex(Parser.JAVADOCEND); setupLex(Parser.IMPORT); setupLex(Parser.IDENTIFIER, "anotherpackage"); setupLex(Parser.DOT); setupLex(Parser.IDENTIFIER, "Something"); setupLex(Parser.SEMI); setupLex(Parser.JAVADOCSTART); setupLex(Parser.JAVADOCLINE, "javadoc5"); setupLex(Parser.JAVADOCEND); setupLex(Parser.JAVADOCSTART); setupLex(Parser.JAVADOCLINE, "javadoc6"); setupLex(Parser.JAVADOCEND); setupLex(Parser.IMPORT); setupLex(Parser.IDENTIFIER, "elsewhere"); setupLex(Parser.DOT); setupLex(Parser.STAR); setupLex(Parser.SEMI); setupLex(Parser.JAVADOCSTART); setupLex(Parser.JAVADOCLINE, "javadoc7"); setupLex(Parser.JAVADOCEND); setupLex(Parser.JAVADOCSTART); setupLex(Parser.JAVADOCLINE, "javadoc8"); setupLex(Parser.JAVADOCEND); setupLex(Parser.PUBLIC); setupLex(Parser.CLASS); setupLex(Parser.IDENTIFIER, "MyClass"); setupLex(Parser.BRACEOPEN); setupLex(Parser.BRACECLOSE); setupLex(Parser.JAVADOCSTART); setupLex(Parser.JAVADOCLINE, "javadoc9"); setupLex(Parser.JAVADOCEND); setupLex(Parser.JAVADOCSTART); setupLex(Parser.JAVADOCLINE, "javadoc10"); setupLex(Parser.JAVADOCEND); setupLex(0); // expectations ClassDef cls = new ClassDef(); cls.name = "MyClass"; cls.modifiers.add("public"); builder.addExpectedBeginClassValues(cls); builder.addExpectedAddJavaDocValues("javadoc1"); builder.addExpectedAddJavaDocValues("javadoc2"); builder.addExpectedAddJavaDocValues("javadoc3"); builder.addExpectedAddJavaDocValues("javadoc4"); builder.addExpectedAddJavaDocValues("javadoc5"); builder.addExpectedAddJavaDocValues("javadoc6"); builder.addExpectedAddJavaDocValues("javadoc7"); builder.addExpectedAddJavaDocValues("javadoc8"); builder.addExpectedAddJavaDocValues("javadoc9"); builder.addExpectedAddJavaDocValues("javadoc10"); // execute Parser parser = new Parser(lexer, builder); parser.parse(); // verify builder.verify(); } public void testSimpleVoidMethod() throws Exception { // setup values setupLex(Parser.CLASS); setupLex(Parser.IDENTIFIER, "MyClass"); setupLex(Parser.BRACEOPEN); setupLex(Parser.IDENTIFIER, "void"); setupLex(Parser.IDENTIFIER, "doSomething"); setupLex(Parser.PARENOPEN); setupLex(Parser.PARENCLOSE); setupLex(Parser.CODEBLOCK); setupLex(Parser.BRACECLOSE); setupLex(0); // expectations MethodDef mth = new MethodDef(); mth.name = "doSomething"; mth.returnType = new TypeDef("void"); builder.addExpectedAddMethodValues(mth); // execute Parser parser = new Parser(lexer, builder); parser.parse(); // verify builder.verify(); } public void testSimpleVoidMethodWithNoCode() throws Exception { // setup values setupLex(Parser.CLASS); setupLex(Parser.IDENTIFIER, "MyClass"); setupLex(Parser.BRACEOPEN); setupLex(Parser.IDENTIFIER, "void"); setupLex(Parser.IDENTIFIER, "doSomething"); setupLex(Parser.PARENOPEN); setupLex(Parser.PARENCLOSE); setupLex(Parser.SEMI); setupLex(Parser.BRACECLOSE); setupLex(0); // expectations MethodDef mth = new MethodDef(); mth.name = "doSomething"; mth.returnType = new TypeDef("void"); builder.addExpectedAddMethodValues(mth); // execute Parser parser = new Parser(lexer, builder); parser.parse(); // verify builder.verify(); } public void testSimpleMethodReturningSomething() throws Exception { // setup values setupLex(Parser.CLASS); setupLex(Parser.IDENTIFIER, "MyClass"); setupLex(Parser.BRACEOPEN); setupLex(Parser.IDENTIFIER, "Something"); setupLex(Parser.IDENTIFIER, "doSomething"); setupLex(Parser.PARENOPEN); setupLex(Parser.PARENCLOSE); setupLex(Parser.CODEBLOCK); setupLex(Parser.BRACECLOSE); setupLex(0); // expectations MethodDef mth = new MethodDef(); mth.name = "doSomething"; mth.returnType = new TypeDef("Something"); builder.addExpectedAddMethodValues(mth); // execute Parser parser = new Parser(lexer, builder); parser.parse(); // verify builder.verify(); } public void testSimpleMethodReturningSomethingFullyQualified() throws Exception { // setup values setupLex(Parser.CLASS); setupLex(Parser.IDENTIFIER, "MyClass"); setupLex(Parser.BRACEOPEN); setupLex(Parser.IDENTIFIER, "com"); setupLex(Parser.DOT); setupLex(Parser.IDENTIFIER, "blah"); setupLex(Parser.DOT); setupLex(Parser.IDENTIFIER, "Something"); setupLex(Parser.IDENTIFIER, "doSomething"); setupLex(Parser.PARENOPEN); setupLex(Parser.PARENCLOSE); setupLex(Parser.CODEBLOCK); setupLex(Parser.BRACECLOSE); setupLex(0); // expectations MethodDef mth = new MethodDef(); mth.name = "doSomething"; mth.returnType = new TypeDef("com.blah.Something"); builder.addExpectedAddMethodValues(mth); // execute Parser parser = new Parser(lexer, builder); parser.parse(); // verify builder.verify(); } public void testSimpleMethodWithAllModifiers() throws Exception { // setup values setupLex(Parser.CLASS); setupLex(Parser.IDENTIFIER, "MyClass"); setupLex(Parser.BRACEOPEN); setupLex(Parser.PUBLIC); setupLex(Parser.PROTECTED); setupLex(Parser.PRIVATE); setupLex(Parser.ABSTRACT); setupLex(Parser.STATIC); setupLex(Parser.FINAL); setupLex(Parser.NATIVE); setupLex(Parser.SYNCHRONIZED); setupLex(Parser.VOLATILE); setupLex(Parser.IDENTIFIER, "com"); setupLex(Parser.DOT); setupLex(Parser.IDENTIFIER, "blah"); setupLex(Parser.DOT); setupLex(Parser.IDENTIFIER, "Something"); setupLex(Parser.IDENTIFIER, "doSomething"); setupLex(Parser.PARENOPEN); setupLex(Parser.PARENCLOSE); setupLex(Parser.CODEBLOCK); setupLex(Parser.BRACECLOSE); setupLex(0); // expectations MethodDef mth = new MethodDef(); mth.name = "doSomething"; mth.returnType = new TypeDef("com.blah.Something"); mth.modifiers.add("public"); mth.modifiers.add("protected"); mth.modifiers.add("private"); mth.modifiers.add("abstract"); mth.modifiers.add("static"); mth.modifiers.add("final"); mth.modifiers.add("native"); mth.modifiers.add("synchronized"); mth.modifiers.add("volatile"); builder.addExpectedAddMethodValues(mth); // execute Parser parser = new Parser(lexer, builder); parser.parse(); // verify builder.verify(); } public void testMethodWithOneArg() throws Exception { // setup values setupLex(Parser.CLASS); setupLex(Parser.IDENTIFIER, "MyClass"); setupLex(Parser.BRACEOPEN); setupLex(Parser.IDENTIFIER, "void"); setupLex(Parser.IDENTIFIER, "doSomething"); setupLex(Parser.PARENOPEN); setupLex(Parser.IDENTIFIER, "int"); setupLex(Parser.IDENTIFIER, "numberOfTimes"); setupLex(Parser.PARENCLOSE); setupLex(Parser.CODEBLOCK); setupLex(Parser.BRACECLOSE); setupLex(0); // expectations MethodDef mth = new MethodDef(); mth.name = "doSomething"; mth.returnType = new TypeDef("void"); FieldDef p1 = new FieldDef(); p1.name = "numberOfTimes"; p1.type = new TypeDef("int"); builder.addExpectedAddMethodValues(mth); builder.addExpectedAddParameterValues( p1 ); // execute Parser parser = new Parser(lexer, builder); parser.parse(); // verify builder.verify(); } public void testMethodWithOneFullyQualifiedArg() throws Exception { // setup values setupLex(Parser.CLASS); setupLex(Parser.IDENTIFIER, "MyClass"); setupLex(Parser.BRACEOPEN); setupLex(Parser.IDENTIFIER, "void"); setupLex(Parser.IDENTIFIER, "doSomething"); setupLex(Parser.PARENOPEN); setupLex(Parser.IDENTIFIER, "java"); setupLex(Parser.DOT); setupLex(Parser.IDENTIFIER, "lang"); setupLex(Parser.DOT); setupLex(Parser.IDENTIFIER, "String"); setupLex(Parser.IDENTIFIER, "numberOfTimes"); setupLex(Parser.PARENCLOSE); setupLex(Parser.CODEBLOCK); setupLex(Parser.BRACECLOSE); setupLex(0); // expectations MethodDef mth = new MethodDef(); mth.name = "doSomething"; mth.returnType = new TypeDef("void"); FieldDef p1 = new FieldDef(); p1.name = "numberOfTimes"; p1.type = new TypeDef("java.lang.String"); builder.addExpectedAddMethodValues(mth); builder.addExpectedAddParameterValues( p1 ); // execute Parser parser = new Parser(lexer, builder); parser.parse(); // verify builder.verify(); } public void testMethodWithTwoArgs() throws Exception { // setup values setupLex(Parser.CLASS); setupLex(Parser.IDENTIFIER, "MyClass"); setupLex(Parser.BRACEOPEN); setupLex(Parser.IDENTIFIER, "void"); setupLex(Parser.IDENTIFIER, "doSomething"); setupLex(Parser.PARENOPEN); setupLex(Parser.IDENTIFIER, "int"); setupLex(Parser.IDENTIFIER, "numberOfTimes"); setupLex(Parser.COMMA); setupLex(Parser.IDENTIFIER, "String"); setupLex(Parser.IDENTIFIER, "name"); setupLex(Parser.PARENCLOSE); setupLex(Parser.CODEBLOCK); setupLex(Parser.BRACECLOSE); setupLex(0); // expectations MethodDef mth = new MethodDef(); mth.name = "doSomething"; mth.returnType = new TypeDef("void"); FieldDef p1 = new FieldDef(); p1.name = "numberOfTimes"; p1.type = new TypeDef("int"); FieldDef p2 = new FieldDef(); p2.name = "name"; p2.type = new TypeDef("String"); builder.addExpectedAddMethodValues(mth); builder.addExpectedAddParameterValues( p1 ); builder.addExpectedAddParameterValues( p2 ); // execute Parser parser = new Parser(lexer, builder); parser.parse(); // verify builder.verify(); } public void testMethodWithThreeArgs() throws Exception { // setup values setupLex(Parser.CLASS); setupLex(Parser.IDENTIFIER, "MyClass"); setupLex(Parser.BRACEOPEN); setupLex(Parser.IDENTIFIER, "void"); setupLex(Parser.IDENTIFIER, "doSomething"); setupLex(Parser.PARENOPEN); setupLex(Parser.IDENTIFIER, "int"); setupLex(Parser.IDENTIFIER, "numberOfTimes"); setupLex(Parser.COMMA); setupLex(Parser.IDENTIFIER, "String"); setupLex(Parser.IDENTIFIER, "name"); setupLex(Parser.COMMA); setupLex(Parser.IDENTIFIER, "boolean"); setupLex(Parser.IDENTIFIER, "x"); setupLex(Parser.PARENCLOSE); setupLex(Parser.CODEBLOCK); setupLex(Parser.BRACECLOSE); setupLex(0); // expectations MethodDef mth = new MethodDef(); mth.name = "doSomething"; mth.returnType = new TypeDef("void"); FieldDef p1 = new FieldDef(); p1.name = "numberOfTimes"; p1.type = new TypeDef("int"); FieldDef p2 = new FieldDef(); p2.name = "name"; p2.type = new TypeDef("String"); FieldDef p3 = new FieldDef(); p3.name = "x"; p3.type = new TypeDef("boolean"); builder.addExpectedAddMethodValues(mth); builder.addExpectedAddParameterValues( p1 ); builder.addExpectedAddParameterValues( p2 ); builder.addExpectedAddParameterValues( p3 ); // execute Parser parser = new Parser(lexer, builder); parser.parse(); // verify builder.verify(); } public void testMethodWithOneArgThatHasModifier() throws Exception { // setup values setupLex(Parser.CLASS); setupLex(Parser.IDENTIFIER, "MyClass"); setupLex(Parser.BRACEOPEN); setupLex(Parser.IDENTIFIER, "void"); setupLex(Parser.IDENTIFIER, "doSomething"); setupLex(Parser.PARENOPEN); setupLex(Parser.FINAL); setupLex(Parser.VOLATILE); setupLex(Parser.IDENTIFIER, "int"); setupLex(Parser.IDENTIFIER, "numberOfTimes"); setupLex(Parser.PARENCLOSE); setupLex(Parser.CODEBLOCK); setupLex(Parser.BRACECLOSE); setupLex(0); // expectations MethodDef mth = new MethodDef(); mth.name = "doSomething"; mth.returnType = new TypeDef("void"); FieldDef p1 = new FieldDef(); p1.name = "numberOfTimes"; p1.type = new TypeDef("int"); p1.modifiers.add("final"); p1.modifiers.add("volatile"); builder.addExpectedAddMethodValues(mth); builder.addExpectedAddParameterValues( p1 ); // execute Parser parser = new Parser(lexer, builder); parser.parse(); // verify builder.verify(); } public void testMethodThrowingOneException() throws Exception { // setup values setupLex(Parser.CLASS); setupLex(Parser.IDENTIFIER, "MyClass"); setupLex(Parser.BRACEOPEN); setupLex(Parser.IDENTIFIER, "void"); setupLex(Parser.IDENTIFIER, "doSomething"); setupLex(Parser.PARENOPEN); setupLex(Parser.PARENCLOSE); setupLex(Parser.THROWS); setupLex(Parser.IDENTIFIER, "IOException"); setupLex(Parser.CODEBLOCK); setupLex(Parser.BRACECLOSE); setupLex(0); // expectations MethodDef mth = new MethodDef(); mth.name = "doSomething"; mth.returnType = new TypeDef("void"); mth.exceptions.add("IOException"); builder.addExpectedAddMethodValues(mth); // execute Parser parser = new Parser(lexer, builder); parser.parse(); // verify builder.verify(); } public void testMethodThrowingTwoExceptions() throws Exception { // setup values setupLex(Parser.CLASS); setupLex(Parser.IDENTIFIER, "MyClass"); setupLex(Parser.BRACEOPEN); setupLex(Parser.IDENTIFIER, "void"); setupLex(Parser.IDENTIFIER, "doSomething"); setupLex(Parser.PARENOPEN); setupLex(Parser.PARENCLOSE); setupLex(Parser.THROWS); setupLex(Parser.IDENTIFIER, "IOException"); setupLex(Parser.COMMA); setupLex(Parser.IDENTIFIER, "MyException"); setupLex(Parser.CODEBLOCK); setupLex(Parser.BRACECLOSE); setupLex(0); // expectations MethodDef mth = new MethodDef(); mth.name = "doSomething"; mth.returnType = new TypeDef("void"); mth.exceptions.add("IOException"); mth.exceptions.add("MyException"); builder.addExpectedAddMethodValues(mth); // execute Parser parser = new Parser(lexer, builder); parser.parse(); // verify builder.verify(); } public void testMethodThrowingThreeExceptions() throws Exception { // setup values setupLex(Parser.CLASS); setupLex(Parser.IDENTIFIER, "MyClass"); setupLex(Parser.BRACEOPEN); setupLex(Parser.IDENTIFIER, "void"); setupLex(Parser.IDENTIFIER, "doSomething"); setupLex(Parser.PARENOPEN); setupLex(Parser.PARENCLOSE); setupLex(Parser.THROWS); setupLex(Parser.IDENTIFIER, "IOException"); setupLex(Parser.COMMA); setupLex(Parser.IDENTIFIER, "MyException"); setupLex(Parser.COMMA); setupLex(Parser.IDENTIFIER, "AnotherException"); setupLex(Parser.CODEBLOCK); setupLex(Parser.BRACECLOSE); setupLex(0); // expectations MethodDef mth = new MethodDef(); mth.name = "doSomething"; mth.returnType = new TypeDef("void"); mth.exceptions.add("IOException"); mth.exceptions.add("MyException"); mth.exceptions.add("AnotherException"); builder.addExpectedAddMethodValues(mth); // execute Parser parser = new Parser(lexer, builder); parser.parse(); // verify builder.verify(); } public void testMethodThrowingOneFullyQualifiedException() throws Exception { // setup values setupLex(Parser.CLASS); setupLex(Parser.IDENTIFIER, "MyClass"); setupLex(Parser.BRACEOPEN); setupLex(Parser.IDENTIFIER, "void"); setupLex(Parser.IDENTIFIER, "doSomething"); setupLex(Parser.PARENOPEN); setupLex(Parser.PARENCLOSE); setupLex(Parser.THROWS); setupLex(Parser.IDENTIFIER, "java"); setupLex(Parser.DOT); setupLex(Parser.IDENTIFIER, "io"); setupLex(Parser.DOT); setupLex(Parser.IDENTIFIER, "IOException"); setupLex(Parser.CODEBLOCK); setupLex(Parser.BRACECLOSE); setupLex(0); // expectations MethodDef mth = new MethodDef(); mth.name = "doSomething"; mth.returnType = new TypeDef("void"); mth.exceptions.add("java.io.IOException"); builder.addExpectedAddMethodValues(mth); // execute Parser parser = new Parser(lexer, builder); parser.parse(); // verify builder.verify(); } public void testMethodThrowingTwoFullyQualifiedException() throws Exception { // setup values setupLex(Parser.CLASS); setupLex(Parser.IDENTIFIER, "MyClass"); setupLex(Parser.BRACEOPEN); setupLex(Parser.IDENTIFIER, "void"); setupLex(Parser.IDENTIFIER, "doSomething"); setupLex(Parser.PARENOPEN); setupLex(Parser.PARENCLOSE); setupLex(Parser.THROWS); setupLex(Parser.IDENTIFIER, "java"); setupLex(Parser.DOT); setupLex(Parser.IDENTIFIER, "io"); setupLex(Parser.DOT); setupLex(Parser.IDENTIFIER, "IOException"); setupLex(Parser.COMMA); setupLex(Parser.IDENTIFIER, "java"); setupLex(Parser.DOT); setupLex(Parser.IDENTIFIER, "lang"); setupLex(Parser.DOT); setupLex(Parser.IDENTIFIER, "RuntimeException"); setupLex(Parser.CODEBLOCK); setupLex(Parser.BRACECLOSE); setupLex(0); // expectations MethodDef mth = new MethodDef(); mth.name = "doSomething"; mth.returnType = new TypeDef("void"); mth.exceptions.add("java.io.IOException"); mth.exceptions.add("java.lang.RuntimeException"); builder.addExpectedAddMethodValues(mth); // execute Parser parser = new Parser(lexer, builder); parser.parse(); // verify builder.verify(); } public void testDefaultConstructor() throws Exception { // setup values setupLex(Parser.CLASS); setupLex(Parser.IDENTIFIER, "MyClass"); setupLex(Parser.BRACEOPEN); setupLex(Parser.IDENTIFIER, "MyClass"); setupLex(Parser.PARENOPEN); setupLex(Parser.PARENCLOSE); setupLex(Parser.CODEBLOCK); setupLex(Parser.BRACECLOSE); setupLex(0); // expectations MethodDef mth = new MethodDef(); mth.name = "MyClass"; mth.constructor = true; builder.addExpectedAddMethodValues(mth); // execute Parser parser = new Parser(lexer, builder); parser.parse(); // verify builder.verify(); } public void testPublicConstructorWithParam() throws Exception { // setup values setupLex(Parser.CLASS); setupLex(Parser.IDENTIFIER, "MyClass"); setupLex(Parser.BRACEOPEN); setupLex(Parser.PUBLIC); setupLex(Parser.IDENTIFIER, "MyClass"); setupLex(Parser.PARENOPEN); setupLex(Parser.IDENTIFIER, "int"); setupLex(Parser.IDENTIFIER, "count"); setupLex(Parser.PARENCLOSE); setupLex(Parser.CODEBLOCK); setupLex(Parser.BRACECLOSE); setupLex(0); // expectations MethodDef mth = new MethodDef(); mth.name = "MyClass"; mth.constructor = true; mth.modifiers.add("public"); FieldDef p1 = new FieldDef(); p1.name = "count"; p1.type = new TypeDef("int"); builder.addExpectedAddMethodValues(mth); builder.addExpectedAddParameterValues( p1 ); // execute Parser parser = new Parser(lexer, builder); parser.parse(); // verify builder.verify(); } public void testConstructorWithMultipleParams() throws Exception { // setup values setupLex(Parser.CLASS); setupLex(Parser.IDENTIFIER, "MyClass"); setupLex(Parser.BRACEOPEN); setupLex(Parser.PUBLIC); setupLex(Parser.IDENTIFIER, "MyClass"); setupLex(Parser.PARENOPEN); setupLex(Parser.IDENTIFIER, "int"); setupLex(Parser.IDENTIFIER, "count"); setupLex(Parser.COMMA); setupLex(Parser.IDENTIFIER, "java"); setupLex(Parser.DOT); setupLex(Parser.IDENTIFIER, "lang"); setupLex(Parser.DOT); setupLex(Parser.IDENTIFIER, "String"); setupLex(Parser.IDENTIFIER, "thingy"); setupLex(Parser.PARENCLOSE); setupLex(Parser.CODEBLOCK); setupLex(Parser.BRACECLOSE); setupLex(0); // expectations MethodDef mth = new MethodDef(); mth.name = "MyClass"; mth.constructor = true; mth.modifiers.add("public"); FieldDef p1 = new FieldDef(); p1.name = "count"; p1.type = new TypeDef("int"); FieldDef p2 = new FieldDef(); p2.name = "thingy"; p2.type = new TypeDef("java.lang.String"); builder.addExpectedAddMethodValues(mth); builder.addExpectedAddParameterValues( p1 ); builder.addExpectedAddParameterValues( p2 ); // execute Parser parser = new Parser(lexer, builder); parser.parse(); // verify builder.verify(); } public void testConstructorWithException() throws Exception { // setup values setupLex(Parser.CLASS); setupLex(Parser.IDENTIFIER, "MyClass"); setupLex(Parser.BRACEOPEN); setupLex(Parser.IDENTIFIER, "MyClass"); setupLex(Parser.PARENOPEN); setupLex(Parser.PARENCLOSE); setupLex(Parser.THROWS); setupLex(Parser.IDENTIFIER, "SomeException"); setupLex(Parser.CODEBLOCK); setupLex(Parser.BRACECLOSE); setupLex(0); // expectations MethodDef mth = new MethodDef(); mth.name = "MyClass"; mth.constructor = true; mth.exceptions.add("SomeException"); builder.addExpectedAddMethodValues(mth); // execute Parser parser = new Parser(lexer, builder); parser.parse(); // verify builder.verify(); } public void testConstructorWithMultipleException() throws Exception { // setup values setupLex(Parser.CLASS); setupLex(Parser.IDENTIFIER, "MyClass"); setupLex(Parser.BRACEOPEN); setupLex(Parser.IDENTIFIER, "MyClass"); setupLex(Parser.PARENOPEN); setupLex(Parser.PARENCLOSE); setupLex(Parser.THROWS); setupLex(Parser.IDENTIFIER, "java"); setupLex(Parser.DOT); setupLex(Parser.IDENTIFIER, "io"); setupLex(Parser.DOT); setupLex(Parser.IDENTIFIER, "IOException"); setupLex(Parser.COMMA); setupLex(Parser.IDENTIFIER, "SomeException"); setupLex(Parser.CODEBLOCK); setupLex(Parser.BRACECLOSE); setupLex(0); // expectations MethodDef mth = new MethodDef(); mth.name = "MyClass"; mth.constructor = true; mth.exceptions.add("SomeException"); mth.exceptions.add("java.io.IOException"); builder.addExpectedAddMethodValues(mth); // execute Parser parser = new Parser(lexer, builder); parser.parse(); // verify builder.verify(); } public void testField() throws Exception { // setup values setupLex(Parser.CLASS); setupLex(Parser.IDENTIFIER, "MyClass"); setupLex(Parser.BRACEOPEN); setupLex(Parser.IDENTIFIER, "int"); setupLex(Parser.IDENTIFIER, "count"); setupLex(Parser.SEMI); setupLex(Parser.BRACECLOSE); setupLex(0); // expectations FieldDef fld = new FieldDef(); fld.name = "count"; fld.type = new TypeDef("int"); builder.addExpectedAddFieldValues(fld); // execute Parser parser = new Parser(lexer, builder); parser.parse(); // verify builder.verify(); } public void testFieldFullyQualified() throws Exception { // setup values setupLex(Parser.CLASS); setupLex(Parser.IDENTIFIER, "MyClass"); setupLex(Parser.BRACEOPEN); setupLex(Parser.IDENTIFIER, "java"); setupLex(Parser.DOT); setupLex(Parser.IDENTIFIER, "lang"); setupLex(Parser.DOT); setupLex(Parser.IDENTIFIER, "String"); setupLex(Parser.IDENTIFIER, "count"); setupLex(Parser.SEMI); setupLex(Parser.BRACECLOSE); setupLex(0); // expectations FieldDef fld = new FieldDef(); fld.name = "count"; fld.type = new TypeDef("java.lang.String"); builder.addExpectedAddFieldValues(fld); // execute Parser parser = new Parser(lexer, builder); parser.parse(); // verify builder.verify(); } public void testFieldWithModifiers() throws Exception { // setup values setupLex(Parser.CLASS); setupLex(Parser.IDENTIFIER, "MyClass"); setupLex(Parser.BRACEOPEN); setupLex(Parser.PUBLIC); setupLex(Parser.PROTECTED); setupLex(Parser.PRIVATE); setupLex(Parser.STATIC); setupLex(Parser.FINAL); setupLex(Parser.TRANSIENT); setupLex(Parser.STRICTFP); setupLex(Parser.IDENTIFIER, "int"); setupLex(Parser.IDENTIFIER, "count"); setupLex(Parser.SEMI); setupLex(Parser.BRACECLOSE); setupLex(0); // expectations FieldDef fld = new FieldDef(); fld.name = "count"; fld.type = new TypeDef("int"); fld.modifiers.add("public"); fld.modifiers.add("protected"); fld.modifiers.add("private"); fld.modifiers.add("static"); fld.modifiers.add("final"); fld.modifiers.add("transient"); fld.modifiers.add("strictfp"); builder.addExpectedAddFieldValues(fld); // execute Parser parser = new Parser(lexer, builder); parser.parse(); // verify builder.verify(); } public void testFieldWithMultipleDefinitionsOnOneLine() throws Exception { // setup values setupLex(Parser.CLASS); setupLex(Parser.IDENTIFIER, "MyClass"); setupLex(Parser.BRACEOPEN); setupLex(Parser.IDENTIFIER, "String"); setupLex(Parser.IDENTIFIER, "thing"); setupLex(Parser.COMMA); setupLex(Parser.IDENTIFIER, "another"); setupLex(Parser.SEMI); setupLex(Parser.BRACECLOSE); setupLex(0); // expectations FieldDef fld1 = new FieldDef(); fld1.name = "thing"; fld1.type = new TypeDef("String"); builder.addExpectedAddFieldValues(fld1); FieldDef fld2 = new FieldDef(); fld2.name = "another"; fld2.type = new TypeDef("String"); builder.addExpectedAddFieldValues(fld2); // execute Parser parser = new Parser(lexer, builder); parser.parse(); // verify builder.verify(); } public void testFieldWithSimpleGenericType() throws Exception { // setup values setupLex(Parser.CLASS); setupLex(Parser.IDENTIFIER, "MyClass"); setupLex(Parser.BRACEOPEN); setupLex(Parser.IDENTIFIER, "List"); setupLex(Parser.LESSTHAN); setupLex(Parser.IDENTIFIER, "String"); setupLex(Parser.GREATERTHAN); setupLex(Parser.IDENTIFIER, "l"); setupLex(Parser.SEMI); setupLex(Parser.BRACECLOSE); setupLex(0); // expectations FieldDef fld = new FieldDef(); fld.name = "l"; fld.type = new TypeDef("List"); fld.type.actualArgumentTypes = new ArrayList(); fld.type.actualArgumentTypes.add(new TypeDef("String")); builder.addExpectedAddFieldValues(fld); // execute Parser parser = new Parser(lexer, builder); parser.parse(); // verify builder.verify(); } public void testFieldWithWildcardGenericType() throws Exception { // setup values setupLex(Parser.CLASS); setupLex(Parser.IDENTIFIER, "MyClass"); setupLex(Parser.BRACEOPEN); setupLex(Parser.IDENTIFIER, "List"); setupLex(Parser.LESSTHAN); setupLex(Parser.QUERY); setupLex(Parser.EXTENDS); setupLex(Parser.IDENTIFIER, "A"); setupLex(Parser.GREATERTHAN); setupLex(Parser.IDENTIFIER, "l"); setupLex(Parser.SEMI); setupLex(Parser.BRACECLOSE); setupLex(0); // expectations FieldDef fld = new FieldDef(); fld.name = "l"; fld.type = new TypeDef("List"); fld.type.actualArgumentTypes = new ArrayList(); fld.type.actualArgumentTypes.add(new WildcardTypeDef(new TypeDef("A"), "extends")); builder.addExpectedAddFieldValues(fld); // execute Parser parser = new Parser(lexer, builder); parser.parse(); // verify builder.verify(); } public void testStaticBlock() throws Exception { // setup values setupLex(Parser.CLASS); setupLex(Parser.IDENTIFIER, "MyClass"); setupLex(Parser.BRACEOPEN); setupLex(Parser.STATIC); setupLex(Parser.CODEBLOCK); // a random method afterwards setupLex(Parser.IDENTIFIER, "void"); setupLex(Parser.IDENTIFIER, "doStuff"); setupLex(Parser.PARENOPEN); setupLex(Parser.PARENCLOSE); setupLex(Parser.SEMI); setupLex(Parser.BRACECLOSE); setupLex(0); // expect no the method, and it shouldn't be static. MethodDef method = new MethodDef(); method.name = "doStuff"; method.returnType = new TypeDef("void"); builder.addExpectedAddMethodValues(method); // execute Parser parser = new Parser(lexer, builder); parser.parse(); // verify builder.verify(); } public void testInnerClass() throws Exception { // setup values setupLex(Parser.CLASS); setupLex(Parser.IDENTIFIER, "MyClass"); setupLex(Parser.BRACEOPEN); setupLex(Parser.CLASS); setupLex(Parser.IDENTIFIER, "InnerCls"); setupLex(Parser.BRACEOPEN); setupLex(Parser.BRACECLOSE); setupLex(Parser.BRACECLOSE); setupLex(Parser.CLASS); setupLex(Parser.IDENTIFIER, "AnotherClass"); setupLex(Parser.BRACEOPEN); setupLex(Parser.BRACECLOSE); setupLex(0); // expectations builder.setExpectedBeginClassCalls(3); ClassDef cls = new ClassDef(); cls.name = "MyClass"; builder.addExpectedBeginClassValues(cls); ClassDef cls2 = new ClassDef(); cls2.name = "InnerCls"; builder.addExpectedBeginClassValues(cls2); ClassDef cls3 = new ClassDef(); cls3.name = "AnotherClass"; builder.addExpectedBeginClassValues(cls3); // execute Parser parser = new Parser(lexer, builder); parser.parse(); // verify builder.verify(); } public void testRogueSemiColon() throws Exception { // setup values setupLex(Parser.CLASS); setupLex(Parser.IDENTIFIER, "MyClass"); setupLex(Parser.BRACEOPEN); setupLex(Parser.SEMI); setupLex(Parser.BRACECLOSE); setupLex(0); // expectations // execute Parser parser = new Parser(lexer, builder); parser.parse(); // verify builder.verify(); } public void testFieldNotArray() throws Exception { // setup values setupLex(Parser.CLASS); setupLex(Parser.IDENTIFIER, "x"); setupLex(Parser.BRACEOPEN); setupLex(Parser.IDENTIFIER, "int"); setupLex(Parser.IDENTIFIER, "count"); setupLex(Parser.SEMI); setupLex(Parser.BRACECLOSE); setupLex(0); // expectations FieldDef fld = new FieldDef(); fld.name = "count"; fld.type = new TypeDef("int"); fld.dimensions = 0; builder.addExpectedAddFieldValues(fld); // execute Parser parser = new Parser(lexer, builder); parser.parse(); // verify builder.verify(); } public void testFieldArrayOnType() throws Exception { // setup values setupLex(Parser.CLASS); setupLex(Parser.IDENTIFIER, "x"); setupLex(Parser.BRACEOPEN); setupLex(Parser.IDENTIFIER, "int"); setupLex(Parser.SQUAREOPEN); setupLex(Parser.SQUARECLOSE); setupLex(Parser.IDENTIFIER, "count"); setupLex(Parser.SEMI); setupLex(Parser.BRACECLOSE); setupLex(0); // expectations FieldDef fld = new FieldDef(); fld.name = "count"; fld.type = new TypeDef("int"); fld.dimensions = 1; builder.addExpectedAddFieldValues(fld); // execute Parser parser = new Parser(lexer, builder); parser.parse(); // verify builder.verify(); } public void testField2dArrayOnType() throws Exception { // setup values setupLex(Parser.CLASS); setupLex(Parser.IDENTIFIER, "x"); setupLex(Parser.BRACEOPEN); setupLex(Parser.IDENTIFIER, "int"); setupLex(Parser.SQUAREOPEN); setupLex(Parser.SQUARECLOSE); setupLex(Parser.SQUAREOPEN); setupLex(Parser.SQUARECLOSE); setupLex(Parser.IDENTIFIER, "count"); setupLex(Parser.SEMI); setupLex(Parser.BRACECLOSE); setupLex(0); // expectations FieldDef fld = new FieldDef(); fld.name = "count"; fld.type = new TypeDef("int"); fld.dimensions = 2; builder.addExpectedAddFieldValues(fld); // execute Parser parser = new Parser(lexer, builder); parser.parse(); // verify builder.verify(); } public void testFieldArrayOnName() throws Exception { // setup values setupLex(Parser.CLASS); setupLex(Parser.IDENTIFIER, "x"); setupLex(Parser.BRACEOPEN); setupLex(Parser.IDENTIFIER, "int"); setupLex(Parser.IDENTIFIER, "count"); setupLex(Parser.SQUAREOPEN); setupLex(Parser.SQUARECLOSE); setupLex(Parser.SEMI); setupLex(Parser.BRACECLOSE); setupLex(0); // expectations FieldDef fld = new FieldDef(); fld.name = "count"; fld.type = new TypeDef("int"); fld.dimensions = 1; builder.addExpectedAddFieldValues(fld); // execute Parser parser = new Parser(lexer, builder); parser.parse(); // verify builder.verify(); } public void testField3dArrayOnTypeAndName() throws Exception { // setup values setupLex(Parser.CLASS); setupLex(Parser.IDENTIFIER, "x"); setupLex(Parser.BRACEOPEN); setupLex(Parser.IDENTIFIER, "int"); setupLex(Parser.SQUAREOPEN); setupLex(Parser.SQUARECLOSE); setupLex(Parser.SQUAREOPEN); setupLex(Parser.SQUARECLOSE); setupLex(Parser.IDENTIFIER, "count"); setupLex(Parser.SQUAREOPEN); setupLex(Parser.SQUARECLOSE); setupLex(Parser.SEMI); setupLex(Parser.BRACECLOSE); setupLex(0); // expectations FieldDef fld = new FieldDef(); fld.name = "count"; fld.type = new TypeDef("int"); fld.dimensions = 3; builder.addExpectedAddFieldValues(fld); // execute Parser parser = new Parser(lexer, builder); parser.parse(); // verify builder.verify(); } public void testFieldArrayThenAnotherNonArray() throws Exception { // setup values setupLex(Parser.CLASS); setupLex(Parser.IDENTIFIER, "x"); setupLex(Parser.BRACEOPEN); setupLex(Parser.IDENTIFIER, "int"); setupLex(Parser.IDENTIFIER, "count"); setupLex(Parser.SQUAREOPEN); setupLex(Parser.SQUARECLOSE); setupLex(Parser.SEMI); setupLex(Parser.IDENTIFIER, "int"); setupLex(Parser.IDENTIFIER, "count2"); setupLex(Parser.SEMI); setupLex(Parser.BRACECLOSE); setupLex(0); // expectations FieldDef fld = new FieldDef(); fld.name = "count"; fld.type = new TypeDef("int"); fld.dimensions = 1; FieldDef fld2 = new FieldDef(); fld2.name = "count2"; fld2.type = new TypeDef("int"); fld2.dimensions = 0; builder.addExpectedAddFieldValues(fld); builder.addExpectedAddFieldValues(fld2); // execute Parser parser = new Parser(lexer, builder); parser.parse(); // verify builder.verify(); } public void testMethodNoArray() throws Exception { // setup values setupLex(Parser.CLASS); setupLex(Parser.IDENTIFIER, "x"); setupLex(Parser.BRACEOPEN); setupLex(Parser.IDENTIFIER, "int"); setupLex(Parser.IDENTIFIER, "count"); setupLex(Parser.PARENOPEN); setupLex(Parser.PARENCLOSE); setupLex(Parser.SEMI); setupLex(Parser.BRACECLOSE); setupLex(0); // expectations MethodDef mth = new MethodDef(); mth.name = "count"; mth.returnType = new TypeDef("int"); mth.dimensions = 0; builder.addExpectedAddMethodValues(mth); // execute Parser parser = new Parser(lexer, builder); parser.parse(); // verify builder.verify(); } public void testMethodArray() throws Exception { // setup values setupLex(Parser.CLASS); setupLex(Parser.IDENTIFIER, "x"); setupLex(Parser.BRACEOPEN); setupLex(Parser.IDENTIFIER, "int"); setupLex(Parser.SQUAREOPEN); setupLex(Parser.SQUARECLOSE); setupLex(Parser.IDENTIFIER, "count"); setupLex(Parser.PARENOPEN); setupLex(Parser.PARENCLOSE); setupLex(Parser.SEMI); setupLex(Parser.BRACECLOSE); setupLex(0); // expectations MethodDef mth = new MethodDef(); mth.name = "count"; mth.returnType = new TypeDef("int"); mth.dimensions = 1; builder.addExpectedAddMethodValues(mth); // execute Parser parser = new Parser(lexer, builder); parser.parse(); // verify builder.verify(); } public void testMethodWithArrayDefinedAtEnd() throws Exception { // It is legal in Java to define a method like this: // String doStuff()[] { // ... which is equivalent to: // String[] doStuff() { // This is done in some places in the JDK. setupLex(Parser.CLASS); setupLex(Parser.IDENTIFIER, "x"); setupLex(Parser.BRACEOPEN); setupLex(Parser.IDENTIFIER, "int"); setupLex(Parser.IDENTIFIER, "count"); setupLex(Parser.PARENOPEN); setupLex(Parser.PARENCLOSE); setupLex(Parser.SQUAREOPEN); setupLex(Parser.SQUARECLOSE); setupLex(Parser.SEMI); setupLex(Parser.BRACECLOSE); setupLex(0); // expectations MethodDef mth = new MethodDef(); mth.name = "count"; mth.returnType = new TypeDef("int"); mth.dimensions = 1; builder.addExpectedAddMethodValues(mth); // execute Parser parser = new Parser(lexer, builder); parser.parse(); // verify builder.verify(); } public void testMethodReturningArrayWithParamNoArray() throws Exception { // setup values setupLex(Parser.CLASS); setupLex(Parser.IDENTIFIER, "x"); setupLex(Parser.BRACEOPEN); setupLex(Parser.IDENTIFIER, "int"); setupLex(Parser.SQUAREOPEN); setupLex(Parser.SQUARECLOSE); setupLex(Parser.IDENTIFIER, "count"); setupLex(Parser.PARENOPEN); setupLex(Parser.IDENTIFIER, "int"); setupLex(Parser.IDENTIFIER, "p1"); setupLex(Parser.PARENCLOSE); setupLex(Parser.SEMI); setupLex(Parser.BRACECLOSE); setupLex(0); // expectations MethodDef mth = new MethodDef(); mth.name = "count"; mth.returnType = new TypeDef("int"); mth.dimensions = 1; FieldDef p1 = new FieldDef(); p1.name = "p1"; p1.type = new TypeDef("int"); p1.dimensions = 0; builder.addExpectedAddMethodValues(mth); builder.addExpectedAddParameterValues( p1 ); // execute Parser parser = new Parser(lexer, builder); parser.parse(); // verify builder.verify(); } public void testMethodReturningNoArrayWithParamArray() throws Exception { // setup values setupLex(Parser.CLASS); setupLex(Parser.IDENTIFIER, "x"); setupLex(Parser.BRACEOPEN); setupLex(Parser.IDENTIFIER, "int"); setupLex(Parser.IDENTIFIER, "count"); setupLex(Parser.PARENOPEN); setupLex(Parser.IDENTIFIER, "int"); setupLex(Parser.SQUAREOPEN); setupLex(Parser.SQUARECLOSE); setupLex(Parser.IDENTIFIER, "p1"); setupLex(Parser.PARENCLOSE); setupLex(Parser.SEMI); setupLex(Parser.BRACECLOSE); setupLex(0); // expectations MethodDef mth = new MethodDef(); mth.name = "count"; mth.returnType = new TypeDef("int"); mth.dimensions = 0; FieldDef p1 = new FieldDef(); p1.name = "p1"; p1.type = new TypeDef("int"); p1.dimensions = 1; builder.addExpectedAddMethodValues(mth); builder.addExpectedAddParameterValues( p1 ); // execute Parser parser = new Parser(lexer, builder); parser.parse(); // verify builder.verify(); } public void testMethodReturningArrayWithParam2dArray() throws Exception { // setup values setupLex(Parser.CLASS); setupLex(Parser.IDENTIFIER, "x"); setupLex(Parser.BRACEOPEN); setupLex(Parser.IDENTIFIER, "int"); setupLex(Parser.SQUAREOPEN); setupLex(Parser.SQUARECLOSE); setupLex(Parser.IDENTIFIER, "count"); setupLex(Parser.PARENOPEN); setupLex(Parser.IDENTIFIER, "int"); setupLex(Parser.SQUAREOPEN); setupLex(Parser.SQUARECLOSE); setupLex(Parser.SQUAREOPEN); setupLex(Parser.SQUARECLOSE); setupLex(Parser.IDENTIFIER, "p1"); setupLex(Parser.PARENCLOSE); setupLex(Parser.SEMI); setupLex(Parser.BRACECLOSE); setupLex(0); // expectations MethodDef mth = new MethodDef(); mth.name = "count"; mth.returnType = new TypeDef("int"); mth.dimensions = 1; FieldDef p1 = new FieldDef(); p1.name = "p1"; p1.type = new TypeDef("int"); p1.dimensions = 2; builder.addExpectedAddMethodValues(mth); builder.addExpectedAddParameterValues( p1 ); // execute Parser parser = new Parser(lexer, builder); parser.parse(); // verify builder.verify(); } public void testMethodWithVarArgsParameter() throws Exception { // setup values setupLex(Parser.CLASS); setupLex(Parser.IDENTIFIER, "x"); setupLex(Parser.BRACEOPEN); setupLex(Parser.IDENTIFIER, "void"); setupLex(Parser.IDENTIFIER, "doStuff"); setupLex(Parser.PARENOPEN); setupLex(Parser.IDENTIFIER, "int"); setupLex(Parser.DOTDOTDOT); setupLex(Parser.IDENTIFIER, "stuff"); setupLex(Parser.PARENCLOSE); setupLex(Parser.SEMI); setupLex(Parser.BRACECLOSE); setupLex(0); // expectations MethodDef mth = new MethodDef(); mth.name = "doStuff"; mth.returnType = new TypeDef("void"); FieldDef p1 = new FieldDef(); p1.name = "stuff"; p1.type = new TypeDef("int"); p1.dimensions = 0; p1.isVarArgs = true; builder.addExpectedAddMethodValues(mth); builder.addExpectedAddParameterValues(p1); // execute Parser parser = new Parser(lexer, builder); parser.parse(); // verify builder.verify(); } public void testEnumWithConstructors() throws Exception { setupLex(Parser.ENUM); setupLex(Parser.IDENTIFIER, "x"); setupLex(Parser.BRACEOPEN); setupLex(Parser.IDENTIFIER, "a"); setupLex(Parser.PARENBLOCK); setupLex(Parser.SEMI); setupLex(Parser.IDENTIFIER, "int"); setupLex(Parser.IDENTIFIER, "someField"); setupLex(Parser.SEMI); setupLex(Parser.BRACECLOSE); setupLex(0); // execute Parser parser = new Parser(lexer, builder); parser.parse(); // verify builder.verify(); } public void testEnumEndingWithExtraComma() throws Exception { setupLex(Parser.ENUM); setupLex(Parser.IDENTIFIER, "x"); setupLex(Parser.BRACEOPEN); setupLex(Parser.IDENTIFIER, "a"); setupLex(Parser.COMMA); setupLex(Parser.BRACECLOSE); setupLex(0); // execute Parser parser = new Parser(lexer, builder); parser.parse(); // verify builder.verify(); } private void setupLex(int token, String value) { lexer.setupLex(token); lexer.setupText(value); } private void setupLex(int token) { setupLex(token, null); } } qdox-qdox-1.12.1/src/test/com/thoughtworks/qdox/testdata/000077500000000000000000000000001204551233600234015ustar00rootroot00000000000000qdox-qdox-1.12.1/src/test/com/thoughtworks/qdox/testdata/DefaultCtor.java000066400000000000000000000004421204551233600264600ustar00rootroot00000000000000/* ---------------------------------------------------------------------------- * (c) Volantis Systems Ltd 2007. All Rights Reserved. * ---------------------------------------------------------------------------- */ package com.thoughtworks.qdox.testdata; public class DefaultCtor { } qdox-qdox-1.12.1/src/test/com/thoughtworks/qdox/testdata/PropertyClass.java000066400000000000000000000021661204551233600270630ustar00rootroot00000000000000package com.thoughtworks.qdox.testdata; // used as test data for properties and binary support and other tests /** * @foo bar="zap" * @aslak.foo bar="dodgeme" */ public class PropertyClass extends Superclass { public static boolean aField; static { aField = true; } protected int protectedField; private int privateField; public PropertyClass() { } protected PropertyClass(PropertyClass other) { privateField = other.privateField; } // not a bean property, sice it's static public static String getFoo() { return "foo"; } public boolean isBar() { return aField; } // not a bean property public void set(int i) { } // not a bean property public final String get() { return null; } protected void protectedMethod() { privateField = 2; protectedField = privateMethod(); } private int privateMethod() { return privateField; } } class Superclass { public int shouldntBeInherited; public int getShouldntBeInherited() { return shouldntBeInherited; } }qdox-qdox-1.12.1/src/test/com/thoughtworks/qdox/testdata/Unicode.java000066400000000000000000000001241204551233600256270ustar00rootroot00000000000000package com.thoughtworks.qdox.testdata; class Unicode { String x = "\u0000"; } qdox-qdox-1.12.1/src/test/com/thoughtworks/qdox/traversal/000077500000000000000000000000001204551233600235735ustar00rootroot00000000000000qdox-qdox-1.12.1/src/test/com/thoughtworks/qdox/traversal/TraversalTest.java000066400000000000000000000021611204551233600272410ustar00rootroot00000000000000package com.thoughtworks.qdox.traversal; import junit.framework.TestCase; import com.thoughtworks.qdox.model.JavaClass; import com.thoughtworks.qdox.model.JavaMethod; import com.thoughtworks.qdox.model.AbstractInheritableJavaEntity; import com.thoughtworks.qdox.JavaDocBuilder; import com.thoughtworks.qdox.ant.AbstractQdoxTaskTest; public class TraversalTest extends TestCase { private JavaDocBuilder builder; public TraversalTest(String name) { super(name); } protected void setUp() throws Exception { builder = new JavaDocBuilder(); builder.addSourceTree(AbstractQdoxTaskTest.getUnderJUnitFile("src/java")); } public void testParentClassTraversal() throws Exception { JavaClass javaClass = builder.getClassByName(JavaMethod.class.getName()); JavaClass parentClass = javaClass.getSuperJavaClass(); assertNotNull("Parent class not found", parentClass); assertEquals("Parent class traversal has returned the wrong parent", AbstractInheritableJavaEntity.class.getName(), parentClass.getFullyQualifiedName()); } }