reformat classes

This commit is contained in:
Laurent SCHOELENS 2023-03-21 09:15:55 +01:00
parent d80597d547
commit c8f805bdef
24 changed files with 1942 additions and 1957 deletions

File diff suppressed because it is too large Load Diff

View File

@ -23,8 +23,9 @@ import java.util.HashMap;
import java.util.Map; import java.util.Map;
/** /**
* Class's dot-compatible alias name (for fully qualified class names) * Class's dot-compatible alias name (for fully qualified class names) and
* and printed information * printed information
*
* @version $Revision$ * @version $Revision$
* @author <a href="http://www.spinellis.gr">Diomidis Spinellis</a> * @author <a href="http://www.spinellis.gr">Diomidis Spinellis</a>
*/ */
@ -36,37 +37,35 @@ class ClassInfo {
boolean nodePrinted; boolean nodePrinted;
/** True if the class class node is hidden */ /** True if the class class node is hidden */
boolean hidden; boolean hidden;
/** /**
* The list of classes that share a relation with this one. Contains * The list of classes that share a relation with this one. Contains all the
* all the classes linked with a bi-directional relation , and the ones * classes linked with a bi-directional relation , and the ones referred by a
* referred by a directed relation * directed relation
*/ */
Map<String, RelationPattern> relatedClasses = new HashMap<String, RelationPattern>(); Map<String, RelationPattern> relatedClasses = new HashMap<String, RelationPattern>();
ClassInfo(boolean h) { ClassInfo(boolean h) {
hidden = h; hidden = h;
name = "c" + classNumber; name = "c" + classNumber;
classNumber++; classNumber++;
} }
public void addRelation(String dest, RelationType rt, RelationDirection d) { public void addRelation(String dest, RelationType rt, RelationDirection d) {
RelationPattern ri = relatedClasses.get(dest); RelationPattern ri = relatedClasses.get(dest);
if(ri == null) { if (ri == null) {
ri = new RelationPattern(RelationDirection.NONE); ri = new RelationPattern(RelationDirection.NONE);
relatedClasses.put(dest, ri); relatedClasses.put(dest, ri);
} }
ri.addRelation(rt, d); ri.addRelation(rt, d);
} }
public RelationPattern getRelation(String dest) { public RelationPattern getRelation(String dest) {
return relatedClasses.get(dest); return relatedClasses.get(dest);
} }
/** Start numbering from zero. */ /** Start numbering from zero. */
public static void reset() { public static void reset() {
classNumber = 0; classNumber = 0;
} }
} }

View File

@ -20,19 +20,19 @@ package org.umlgraph.doclet;
import com.sun.javadoc.ClassDoc; import com.sun.javadoc.ClassDoc;
/** /**
* A ClassMatcher is used to check if a class definition matches a * A ClassMatcher is used to check if a class definition matches a specific
* specific condition. The nature of the condition is dependent on * condition. The nature of the condition is dependent on the kind of matcher
* the kind of matcher *
* @author wolf * @author wolf
*/ */
public interface ClassMatcher { public interface ClassMatcher {
/** /**
* Returns the options for the specified class. * Returns the options for the specified class.
*/ */
public boolean matches(ClassDoc cd); public boolean matches(ClassDoc cd);
/** /**
* Returns the options for the specified class. * Returns the options for the specified class.
*/ */
public boolean matches(String name); public boolean matches(String name);
} }

View File

@ -38,6 +38,7 @@ import com.sun.javadoc.RootDoc;
* This class needs to perform quite a bit of computations in order to gather * This class needs to perform quite a bit of computations in order to gather
* the network of class releationships, so you are allowed to reuse it should * the network of class releationships, so you are allowed to reuse it should
* you * you
*
* @author wolf * @author wolf
* *
* @depend - - - DevNullWriter * @depend - - - DevNullWriter
@ -54,25 +55,26 @@ public class ContextMatcher implements ClassMatcher {
/** /**
* Builds the context matcher * Builds the context matcher
* @param root The root doc returned by JavaDoc *
* @param pattern The pattern that will match the "center" of this * @param root The root doc returned by JavaDoc
* context * @param pattern The pattern that will match the "center" of this
* @param keepParentHide If true, parent option hide patterns will be * context
* preserved, so that classes hidden by the options won't * @param keepParentHide If true, parent option hide patterns will be preserved,
* be shown in the context * so that classes hidden by the options won't be shown in
* the context
* @throws IOException * @throws IOException
*/ */
public ContextMatcher(RootDoc root, Pattern pattern, Options options, boolean keepParentHide) throws IOException { public ContextMatcher(RootDoc root, Pattern pattern, Options options, boolean keepParentHide) throws IOException {
this.pattern = pattern; this.pattern = pattern;
this.root = root; this.root = root;
this.keepParentHide = keepParentHide; this.keepParentHide = keepParentHide;
opt = (Options) options.clone(); opt = (Options) options.clone();
opt.setOption(new String[] { "!hide" }); opt.setOption(new String[] { "!hide" });
opt.setOption(new String[] { "!attributes" }); opt.setOption(new String[] { "!attributes" });
opt.setOption(new String[] { "!operations" }); opt.setOption(new String[] { "!operations" });
this.cg = new ClassGraphHack(root, opt); this.cg = new ClassGraphHack(root, opt);
setContextCenter(pattern); setContextCenter(pattern);
} }
/** /**
@ -80,116 +82,119 @@ public class ContextMatcher implements ClassMatcher {
* <p> * <p>
* This can be used to speed up subsequent matching with the same global * This can be used to speed up subsequent matching with the same global
* options, since the class network informations will be reused. * options, since the class network informations will be reused.
*
* @param pattern * @param pattern
*/ */
public void setContextCenter(Pattern pattern) { public void setContextCenter(Pattern pattern) {
// build up the classgraph printing the relations for all of the // build up the classgraph printing the relations for all of the
// classes that make up the "center" of this context // classes that make up the "center" of this context
this.pattern = pattern; this.pattern = pattern;
matched = new ArrayList<ClassDoc>(); matched = new ArrayList<ClassDoc>();
for (ClassDoc cd : root.classes()) { for (ClassDoc cd : root.classes()) {
if (pattern.matcher(cd.toString()).matches()) { if (pattern.matcher(cd.toString()).matches()) {
matched.add(cd); matched.add(cd);
addToGraph(cd); addToGraph(cd);
} }
} }
} }
/** /**
* Adds the specified class to the internal class graph along with its * Adds the specified class to the internal class graph along with its relations
* relations and dependencies, eventually inferring them, according to the * and dependencies, eventually inferring them, according to the Options
* Options specified for this matcher * specified for this matcher
*
* @param cd * @param cd
*/ */
private void addToGraph(ClassDoc cd) { private void addToGraph(ClassDoc cd) {
// avoid adding twice the same class, but don't rely on cg.getClassInfo // avoid adding twice the same class, but don't rely on cg.getClassInfo
// since there are other ways to add a classInfor than printing the class // since there are other ways to add a classInfor than printing the class
if (visited.contains(cd.toString())) if (visited.contains(cd.toString()))
return; return;
visited.add(cd.toString()); visited.add(cd.toString());
cg.printClass(cd, false); cg.printClass(cd, false);
cg.printRelations(cd); cg.printRelations(cd);
if (opt.inferRelationships) if (opt.inferRelationships)
cg.printInferredRelations(cd); cg.printInferredRelations(cd);
if (opt.inferDependencies) if (opt.inferDependencies)
cg.printInferredDependencies(cd); cg.printInferredDependencies(cd);
} }
/** /**
* @see org.umlgraph.doclet.ClassMatcher#matches(com.sun.javadoc.ClassDoc) * @see org.umlgraph.doclet.ClassMatcher#matches(com.sun.javadoc.ClassDoc)
*/ */
public boolean matches(ClassDoc cd) { public boolean matches(ClassDoc cd) {
if (keepParentHide && opt.matchesHideExpression(cd.toString())) if (keepParentHide && opt.matchesHideExpression(cd.toString()))
return false; return false;
// if the class is matched, it's in by default. // if the class is matched, it's in by default.
if (matched.contains(cd)) if (matched.contains(cd))
return true; return true;
// otherwise, add the class to the graph and see if it's associated // otherwise, add the class to the graph and see if it's associated
// with any of the matched classes using the classgraph hack // with any of the matched classes using the classgraph hack
addToGraph(cd); addToGraph(cd);
return matches(cd.toString()); return matches(cd.toString());
} }
/** /**
* @see org.umlgraph.doclet.ClassMatcher#matches(java.lang.String) * @see org.umlgraph.doclet.ClassMatcher#matches(java.lang.String)
*/ */
public boolean matches(String name) { public boolean matches(String name) {
if (pattern.matcher(name).matches()) if (pattern.matcher(name).matches())
return true; return true;
for (ClassDoc mcd : matched) { for (ClassDoc mcd : matched) {
RelationPattern rp = cg.getClassInfo(mcd, true).getRelation(name); RelationPattern rp = cg.getClassInfo(mcd, true).getRelation(name);
if (rp != null && opt.contextRelationPattern.matchesOne(rp)) if (rp != null && opt.contextRelationPattern.matchesOne(rp))
return true; return true;
} }
return false; return false;
} }
/** /**
* A quick hack to compute class dependencies reusing ClassGraph but * A quick hack to compute class dependencies reusing ClassGraph but without
* without generating output. Will be removed once the ClassGraph class * generating output. Will be removed once the ClassGraph class will be split
* will be split into two classes for graph computation and output * into two classes for graph computation and output generation.
* generation. *
* @author wolf * @author wolf
* *
*/ */
private static class ClassGraphHack extends ClassGraph { private static class ClassGraphHack extends ClassGraph {
public ClassGraphHack(RootDoc root, OptionProvider optionProvider) throws IOException { public ClassGraphHack(RootDoc root, OptionProvider optionProvider) throws IOException {
super(root, optionProvider, null); super(root, optionProvider, null);
prologue(); prologue();
} }
@Override @Override
public void prologue() throws IOException { public void prologue() throws IOException {
w = new PrintWriter(new DevNullWriter()); w = new PrintWriter(new DevNullWriter());
} }
} }
/** /**
* Simple dev/null imitation * Simple dev/null imitation
*
* @author wolf * @author wolf
*/ */
private static class DevNullWriter extends Writer { private static class DevNullWriter extends Writer {
@Override @Override
public void write(char[] cbuf, int off, int len) throws IOException { public void write(char[] cbuf, int off, int len) throws IOException {
// nothing to do // nothing to do
} }
@Override @Override
public void flush() throws IOException { public void flush() throws IOException {
// nothing to do // nothing to do
} }
@Override @Override
public void close() throws IOException { public void close() throws IOException {
// nothing to do // nothing to do
} }
} }

View File

@ -14,6 +14,7 @@ import com.sun.javadoc.RootDoc;
* single {@linkplain ContextMatcher}, but provides some extra configuration * single {@linkplain ContextMatcher}, but provides some extra configuration
* such as context highlighting and output path configuration (and it is * such as context highlighting and output path configuration (and it is
* specified in code rather than in javadoc comments). * specified in code rather than in javadoc comments).
*
* @author wolf * @author wolf
* *
*/ */
@ -28,93 +29,89 @@ public class ContextView implements OptionProvider {
private Options packageOptions; private Options packageOptions;
private static final String[] HIDE_OPTIONS = new String[] { "hide" }; private static final String[] HIDE_OPTIONS = new String[] { "hide" };
public ContextView(String outputFolder, ClassDoc cd, RootDoc root, Options parent) public ContextView(String outputFolder, ClassDoc cd, RootDoc root, Options parent) throws IOException {
throws IOException { this.cd = cd;
this.cd = cd; String outputPath = cd.containingPackage().name().replace('.', '/') + "/" + cd.name() + ".dot";
String outputPath = cd.containingPackage().name().replace('.', '/') + "/" + cd.name()
+ ".dot";
// setup options statically, so that we won't need to change them so // setup options statically, so that we won't need to change them so
// often // often
this.globalOptions = parent.getGlobalOptions(); this.globalOptions = parent.getGlobalOptions();
this.packageOptions = parent.getGlobalOptions();
this.packageOptions.showQualified = false;
this.myGlobalOptions = parent.getGlobalOptions(); this.packageOptions = parent.getGlobalOptions();
this.myGlobalOptions.setOption(new String[] { "output", outputPath }); this.packageOptions.showQualified = false;
this.myGlobalOptions.setOption(HIDE_OPTIONS);
this.hideOptions = parent.getGlobalOptions(); this.myGlobalOptions = parent.getGlobalOptions();
this.hideOptions.setOption(HIDE_OPTIONS); this.myGlobalOptions.setOption(new String[] { "output", outputPath });
this.myGlobalOptions.setOption(HIDE_OPTIONS);
this.centerOptions = parent.getGlobalOptions(); this.hideOptions = parent.getGlobalOptions();
this.centerOptions.nodeFillColor = "lemonChiffon"; this.hideOptions.setOption(HIDE_OPTIONS);
this.centerOptions.showQualified = false;
this.matcher = new ContextMatcher(root, Pattern.compile(Pattern.quote(cd.toString())), this.centerOptions = parent.getGlobalOptions();
myGlobalOptions, true); this.centerOptions.nodeFillColor = "lemonChiffon";
this.centerOptions.showQualified = false;
this.matcher = new ContextMatcher(root, Pattern.compile(Pattern.quote(cd.toString())), myGlobalOptions, true);
} }
public void setContextCenter(ClassDoc contextCenter) { public void setContextCenter(ClassDoc contextCenter) {
this.cd = contextCenter; this.cd = contextCenter;
String outputPath = cd.containingPackage().name().replace('.', '/') + "/" + cd.name() String outputPath = cd.containingPackage().name().replace('.', '/') + "/" + cd.name() + ".dot";
+ ".dot"; this.myGlobalOptions.setOption(new String[] { "output", outputPath });
this.myGlobalOptions.setOption(new String[] { "output", outputPath }); matcher.setContextCenter(Pattern.compile(Pattern.quote(cd.toString())));
matcher.setContextCenter(Pattern.compile(Pattern.quote(cd.toString())));
} }
public String getDisplayName() { public String getDisplayName() {
return "Context view for class " + cd; return "Context view for class " + cd;
} }
public Options getGlobalOptions() { public Options getGlobalOptions() {
return myGlobalOptions; return myGlobalOptions;
} }
public Options getOptionsFor(ClassDoc cd) { public Options getOptionsFor(ClassDoc cd) {
Options opt; Options opt;
if (globalOptions.matchesHideExpression(cd.qualifiedName()) if (globalOptions.matchesHideExpression(cd.qualifiedName())
|| !(matcher.matches(cd) || globalOptions.matchesIncludeExpression(cd.qualifiedName()))) { || !(matcher.matches(cd) || globalOptions.matchesIncludeExpression(cd.qualifiedName()))) {
opt = hideOptions; opt = hideOptions;
} else if (cd.equals(this.cd)) { } else if (cd.equals(this.cd)) {
opt = centerOptions; opt = centerOptions;
} else if(cd.containingPackage().equals(this.cd.containingPackage())){ } else if (cd.containingPackage().equals(this.cd.containingPackage())) {
opt = packageOptions; opt = packageOptions;
} else { } else {
opt = globalOptions; opt = globalOptions;
} }
Options optionClone = (Options) opt.clone(); Options optionClone = (Options) opt.clone();
overrideForClass(optionClone, cd); overrideForClass(optionClone, cd);
return optionClone; return optionClone;
} }
public Options getOptionsFor(String name) { public Options getOptionsFor(String name) {
Options opt; Options opt;
if (!matcher.matches(name)) if (!matcher.matches(name))
opt = hideOptions; opt = hideOptions;
else if (name.equals(cd.name())) else if (name.equals(cd.name()))
opt = centerOptions; opt = centerOptions;
else else
opt = globalOptions; opt = globalOptions;
Options optionClone = (Options) opt.clone(); Options optionClone = (Options) opt.clone();
overrideForClass(optionClone, name); overrideForClass(optionClone, name);
return optionClone; return optionClone;
} }
public void overrideForClass(Options opt, ClassDoc cd) { public void overrideForClass(Options opt, ClassDoc cd) {
opt.setOptions(cd); opt.setOptions(cd);
if (opt.matchesHideExpression(cd.qualifiedName()) if (opt.matchesHideExpression(cd.qualifiedName())
|| !(matcher.matches(cd) || opt.matchesIncludeExpression(cd.qualifiedName()))) || !(matcher.matches(cd) || opt.matchesIncludeExpression(cd.qualifiedName())))
opt.setOption(HIDE_OPTIONS); opt.setOption(HIDE_OPTIONS);
if (cd.equals(this.cd)) if (cd.equals(this.cd))
opt.nodeFillColor = "lemonChiffon"; opt.nodeFillColor = "lemonChiffon";
} }
public void overrideForClass(Options opt, String className) { public void overrideForClass(Options opt, String className) {
if (!(matcher.matches(className) || opt.matchesIncludeExpression(className))) if (!(matcher.matches(className) || opt.matchesIncludeExpression(className)))
opt.setOption(HIDE_OPTIONS); opt.setOption(HIDE_OPTIONS);
} }
} }

View File

@ -33,12 +33,12 @@ public enum Font {
// Static initialization of further values. // Static initialization of further values.
static { static {
// use an appropriate font depending on the current operating system // use an appropriate font depending on the current operating system
if (System.getProperty("os.name").toLowerCase().contains("windows")) { if (System.getProperty("os.name").toLowerCase().contains("windows")) {
DEFAULT_FONT = "Arial"; DEFAULT_FONT = "Arial";
} else { } else {
DEFAULT_FONT = "Helvetica"; // TODO: can we use just "sans"? DEFAULT_FONT = "Helvetica"; // TODO: can we use just "sans"?
} }
} }
/** /**
@ -49,53 +49,53 @@ public enum Font {
* @return Wrapped text * @return Wrapped text
*/ */
public String wrap(Options opt, String text) { public String wrap(Options opt, String text) {
if (text.isEmpty() || this == NORMAL) if (text.isEmpty() || this == NORMAL)
return text; return text;
String face = null; String face = null;
double size = -1; double size = -1;
boolean italic = false; boolean italic = false;
switch (this) { switch (this) {
case EDGE: case EDGE:
case NODE: case NODE:
// Not used with the wrap function. // Not used with the wrap function.
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
case ABSTRACT: case ABSTRACT:
italic = opt.nodeFontAbstractItalic; italic = opt.nodeFontAbstractItalic;
case NORMAL: case NORMAL:
break; break;
case CLASS_ABSTRACT: case CLASS_ABSTRACT:
italic = opt.nodeFontAbstractItalic; italic = opt.nodeFontAbstractItalic;
case CLASS: case CLASS:
face = opt.nodeFontClassName; face = opt.nodeFontClassName;
size = opt.nodeFontClassSize; size = opt.nodeFontClassSize;
break; break;
case PACKAGE: case PACKAGE:
face = opt.nodeFontPackageName; face = opt.nodeFontPackageName;
size = opt.nodeFontPackageSize; size = opt.nodeFontPackageSize;
break; break;
case TAG: case TAG:
face = opt.nodeFontTagName; face = opt.nodeFontTagName;
size = opt.nodeFontTagSize; size = opt.nodeFontTagSize;
break; break;
} }
if (face == null && size < 0 && !italic) if (face == null && size < 0 && !italic)
return text; return text;
StringBuilder buf = new StringBuilder(text.length() + 100); StringBuilder buf = new StringBuilder(text.length() + 100);
if (face != null || size > 0) { if (face != null || size > 0) {
buf.append("<font"); buf.append("<font");
if (face != null) if (face != null)
buf.append(" face=\"").append(face).append('"'); buf.append(" face=\"").append(face).append('"');
if (size > 0) if (size > 0)
buf.append(" point-size=\"").append(size).append('"'); buf.append(" point-size=\"").append(size).append('"');
buf.append('>'); buf.append('>');
} }
if (italic) if (italic)
buf.append("<i>"); buf.append("<i>");
buf.append(text); buf.append(text);
if (italic) if (italic)
buf.append("</i>"); buf.append("</i>");
if (face != null || size > 0) if (face != null || size > 0)
buf.append("</font>"); buf.append("</font>");
return buf.toString(); return buf.toString();
} }
} }

View File

@ -6,8 +6,8 @@ import com.sun.javadoc.ClassDoc;
import com.sun.javadoc.RootDoc; import com.sun.javadoc.RootDoc;
/** /**
* Matches every class that implements (directly or indirectly) an * Matches every class that implements (directly or indirectly) an interfaces
* interfaces matched by regular expression provided. * matched by regular expression provided.
*/ */
public class InterfaceMatcher implements ClassMatcher { public class InterfaceMatcher implements ClassMatcher {
@ -15,28 +15,28 @@ public class InterfaceMatcher implements ClassMatcher {
protected Pattern pattern; protected Pattern pattern;
public InterfaceMatcher(RootDoc root, Pattern pattern) { public InterfaceMatcher(RootDoc root, Pattern pattern) {
this.root = root; this.root = root;
this.pattern = pattern; this.pattern = pattern;
} }
public boolean matches(ClassDoc cd) { public boolean matches(ClassDoc cd) {
// if it's the interface we're looking for, match // if it's the interface we're looking for, match
if(cd.isInterface() && pattern.matcher(cd.toString()).matches()) if (cd.isInterface() && pattern.matcher(cd.toString()).matches())
return true; return true;
// for each interface, recurse, since classes and interfaces // for each interface, recurse, since classes and interfaces
// are treated the same in the doclet API // are treated the same in the doclet API
for (ClassDoc iface : cd.interfaces()) for (ClassDoc iface : cd.interfaces())
if(matches(iface)) if (matches(iface))
return true; return true;
// recurse on supeclass, if available // recurse on supeclass, if available
return cd.superclass() == null ? false : matches(cd.superclass()); return cd.superclass() == null ? false : matches(cd.superclass());
} }
public boolean matches(String name) { public boolean matches(String name) {
ClassDoc cd = root.classNamed(name); ClassDoc cd = root.classNamed(name);
return cd == null ? false : matches(cd); return cd == null ? false : matches(cd);
} }
} }

View File

@ -20,8 +20,8 @@ package org.umlgraph.doclet;
import com.sun.javadoc.ClassDoc; import com.sun.javadoc.ClassDoc;
/** /**
* A factory class that builds Options object for general use or for a * A factory class that builds Options object for general use or for a specific
* specific class * class
*/ */
public interface OptionProvider { public interface OptionProvider {
/** /**
@ -51,7 +51,8 @@ public interface OptionProvider {
/** /**
* Returns user displayable name for this option provider. * Returns user displayable name for this option provider.
* <p>Will be used to provide progress feedback on the console * <p>
* Will be used to provide progress feedback on the console
*/ */
public String getDisplayName(); public String getDisplayName();
} }

File diff suppressed because it is too large Load Diff

View File

@ -7,19 +7,19 @@ public class PackageMatcher implements ClassMatcher {
protected PackageDoc packageDoc; protected PackageDoc packageDoc;
public PackageMatcher(PackageDoc packageDoc) { public PackageMatcher(PackageDoc packageDoc) {
super(); super();
this.packageDoc = packageDoc; this.packageDoc = packageDoc;
} }
public boolean matches(ClassDoc cd) { public boolean matches(ClassDoc cd) {
return cd.containingPackage().equals(packageDoc); return cd.containingPackage().equals(packageDoc);
} }
public boolean matches(String name) { public boolean matches(String name) {
for (ClassDoc cd : packageDoc.allClasses()) for (ClassDoc cd : packageDoc.allClasses())
if (cd.qualifiedName().equals(name)) if (cd.qualifiedName().equals(name))
return true; return true;
return false; return false;
} }
} }

View File

@ -12,6 +12,7 @@ import com.sun.javadoc.RootDoc;
* single {@linkplain ClassMatcher}, and provides some extra configuration such * single {@linkplain ClassMatcher}, and provides some extra configuration such
* as output path configuration (and it is specified in code rather than in * as output path configuration (and it is specified in code rather than in
* javadoc comments). * javadoc comments).
*
* @author wolf * @author wolf
* *
*/ */
@ -25,57 +26,57 @@ public class PackageView implements OptionProvider {
private Options opt; private Options opt;
public PackageView(String outputFolder, PackageDoc pd, RootDoc root, OptionProvider parent) { public PackageView(String outputFolder, PackageDoc pd, RootDoc root, OptionProvider parent) {
this.parent = parent; this.parent = parent;
this.pd = pd; this.pd = pd;
this.matcher = new PackageMatcher(pd); this.matcher = new PackageMatcher(pd);
this.opt = parent.getGlobalOptions(); this.opt = parent.getGlobalOptions();
this.opt.setOptions(pd); this.opt.setOptions(pd);
this.outputPath = pd.name().replace('.', '/') + "/" + pd.name() + ".dot"; this.outputPath = pd.name().replace('.', '/') + "/" + pd.name() + ".dot";
} }
public String getDisplayName() { public String getDisplayName() {
return "Package view for package " + pd; return "Package view for package " + pd;
} }
public Options getGlobalOptions() { public Options getGlobalOptions() {
Options go = parent.getGlobalOptions(); Options go = parent.getGlobalOptions();
go.setOption(new String[] { "output", outputPath }); go.setOption(new String[] { "output", outputPath });
go.setOption(HIDE); go.setOption(HIDE);
return go; return go;
} }
public Options getOptionsFor(ClassDoc cd) { public Options getOptionsFor(ClassDoc cd) {
Options go = parent.getGlobalOptions(); Options go = parent.getGlobalOptions();
overrideForClass(go, cd); overrideForClass(go, cd);
return go; return go;
} }
public Options getOptionsFor(String name) { public Options getOptionsFor(String name) {
Options go = parent.getGlobalOptions(); Options go = parent.getGlobalOptions();
overrideForClass(go, name); overrideForClass(go, name);
return go; return go;
} }
public void overrideForClass(Options opt, ClassDoc cd) { public void overrideForClass(Options opt, ClassDoc cd) {
opt.setOptions(cd); opt.setOptions(cd);
boolean inPackage = matcher.matches(cd); boolean inPackage = matcher.matches(cd);
if (inPackage) if (inPackage)
opt.showQualified = false; opt.showQualified = false;
boolean included = inPackage || this.opt.matchesIncludeExpression(cd.qualifiedName()); boolean included = inPackage || this.opt.matchesIncludeExpression(cd.qualifiedName());
if (!included || this.opt.matchesHideExpression(cd.qualifiedName())) if (!included || this.opt.matchesHideExpression(cd.qualifiedName()))
opt.setOption(HIDE); opt.setOption(HIDE);
} }
public void overrideForClass(Options opt, String className) { public void overrideForClass(Options opt, String className) {
opt.showQualified = false; opt.showQualified = false;
boolean inPackage = matcher.matches(className); boolean inPackage = matcher.matches(className);
if (inPackage) if (inPackage)
opt.showQualified = false; opt.showQualified = false;
boolean included = inPackage || this.opt.matchesIncludeExpression(className); boolean included = inPackage || this.opt.matchesIncludeExpression(className);
if (!included || this.opt.matchesHideExpression(className)) if (!included || this.opt.matchesHideExpression(className))
opt.setOption(HIDE); opt.setOption(HIDE);
} }
} }

View File

@ -23,21 +23,22 @@ import com.sun.javadoc.ClassDoc;
/** /**
* Matches classes performing a regular expression match on the qualified class * Matches classes performing a regular expression match on the qualified class
* name * name
*
* @author wolf * @author wolf
*/ */
public class PatternMatcher implements ClassMatcher { public class PatternMatcher implements ClassMatcher {
Pattern pattern; Pattern pattern;
public PatternMatcher(Pattern pattern) { public PatternMatcher(Pattern pattern) {
this.pattern = pattern; this.pattern = pattern;
} }
public boolean matches(ClassDoc cd) { public boolean matches(ClassDoc cd) {
return matches(cd.toString()); return matches(cd.toString());
} }
public boolean matches(String name) { public boolean matches(String name) {
return pattern.matcher(name).matches(); return pattern.matcher(name).matches();
} }
} }

View File

@ -9,32 +9,35 @@ public enum RelationDirection {
/** /**
* Adds the current direction * Adds the current direction
*
* @param d * @param d
* @return * @return
*/ */
public RelationDirection sum(RelationDirection d) { public RelationDirection sum(RelationDirection d) {
// Handle same and nones first: // Handle same and nones first:
return (this == d || d == NONE) ? this : // return (this == d || d == NONE) ? this : //
this == NONE ? d : BOTH; // They are different and not none. this == NONE ? d : BOTH; // They are different and not none.
} }
/** /**
* Returns true if this direction "contains" the specified one, that is, * Returns true if this direction "contains" the specified one, that is, either
* either it's equal to it, or this direction is {@link #BOTH} * it's equal to it, or this direction is {@link #BOTH}
*
* @param d * @param d
* @return * @return
*/ */
public boolean contains(RelationDirection d) { public boolean contains(RelationDirection d) {
return this == BOTH ? true : (d == this); return this == BOTH ? true : (d == this);
} }
/** /**
* Inverts the direction of the relation. Turns IN into OUT and vice-versa, NONE and BOTH * Inverts the direction of the relation. Turns IN into OUT and vice-versa, NONE
* are not changed * and BOTH are not changed
*
* @return * @return
*/ */
public RelationDirection inverse() { public RelationDirection inverse() {
return this == IN ? OUT : this == OUT ? IN : this; return this == IN ? OUT : this == OUT ? IN : this;
} }
}; };

View File

@ -2,6 +2,7 @@ package org.umlgraph.doclet;
/** /**
* A map from relation types to directions * A map from relation types to directions
*
* @author wolf * @author wolf
* *
*/ */
@ -13,38 +14,41 @@ public class RelationPattern {
/** /**
* Creates a new pattern using the same direction for every relation kind * Creates a new pattern using the same direction for every relation kind
*
* @param defaultDirection The direction used to initialize this pattern * @param defaultDirection The direction used to initialize this pattern
*/ */
public RelationPattern(RelationDirection defaultDirection) { public RelationPattern(RelationDirection defaultDirection) {
directions = new RelationDirection[RelationType.values().length]; directions = new RelationDirection[RelationType.values().length];
for (int i = 0; i < directions.length; i++) { for (int i = 0; i < directions.length; i++) {
directions[i] = defaultDirection; directions[i] = defaultDirection;
} }
} }
/** /**
* Adds, eventually merging, a direction for the specified relation type * Adds, eventually merging, a direction for the specified relation type
*
* @param relationType * @param relationType
* @param direction * @param direction
*/ */
public void addRelation(RelationType relationType, RelationDirection direction) { public void addRelation(RelationType relationType, RelationDirection direction) {
int idx = relationType.ordinal(); int idx = relationType.ordinal();
directions[idx] = directions[idx].sum(direction); directions[idx] = directions[idx].sum(direction);
} }
/** /**
* Returns true if this patterns matches at least the direction of one * Returns true if this patterns matches at least the direction of one of the
* of the relations in the other relation patterns. Matching is defined * relations in the other relation patterns. Matching is defined by
* by {@linkplain RelationDirection#contains(RelationDirection)} * {@linkplain RelationDirection#contains(RelationDirection)}
*
* @param relationPattern * @param relationPattern
* @return * @return
*/ */
public boolean matchesOne(RelationPattern relationPattern) { public boolean matchesOne(RelationPattern relationPattern) {
for (int i = 0; i < directions.length; i++) { for (int i = 0; i < directions.length; i++) {
if (directions[i].contains(relationPattern.directions[i])) if (directions[i].contains(relationPattern.directions[i]))
return true; return true;
} }
return false; return false;
} }
} }

View File

@ -27,8 +27,8 @@ public enum RelationType {
/** Enum constructors must be private */ /** Enum constructors must be private */
private RelationType(String style, boolean backorder) { private RelationType(String style, boolean backorder) {
this.lower = toString().toLowerCase(); this.lower = toString().toLowerCase();
this.style = style; this.style = style;
this.backorder = backorder; this.backorder = backorder;
} }
} }

View File

@ -45,10 +45,10 @@ public enum Shape {
/** Initialize the lookup index */ /** Initialize the lookup index */
static { static {
for (Shape s : Shape.values()) { for (Shape s : Shape.values()) {
index.put(s.name(), s); index.put(s.name(), s);
index.put(s.name().toLowerCase(Locale.ROOT), s); index.put(s.name().toLowerCase(Locale.ROOT), s);
} }
} }
/** /**
@ -59,25 +59,25 @@ public enum Shape {
* @return Shape * @return Shape
*/ */
public static Shape of(String s) { public static Shape of(String s) {
Shape shp = index.get(s); Shape shp = index.get(s);
if (shp != null) if (shp != null)
return shp; return shp;
System.err.println("Ignoring invalid shape: " + s); System.err.println("Ignoring invalid shape: " + s);
return CLASS; return CLASS;
} }
/** Enum constructor, must be private! */ /** Enum constructor, must be private! */
private Shape(String style) { private Shape(String style) {
this.style = style; this.style = style;
} }
/** Return the table border required for the shape */ /** Return the table border required for the shape */
public String extraColumn() { public String extraColumn() {
return this == Shape.ACTIVECLASS ? ("<td rowspan=\"10\"></td>") : ""; return this == Shape.ACTIVECLASS ? ("<td rowspan=\"10\"></td>") : "";
} }
/** Return the cell border required for the shape */ /** Return the cell border required for the shape */
public String cellBorder() { public String cellBorder() {
return this == CLASS || this == ACTIVECLASS ? "1" : "0"; return this == CLASS || this == ACTIVECLASS ? "1" : "0";
} }
} }

View File

@ -31,37 +31,37 @@ import java.util.regex.Pattern;
class StringUtil { class StringUtil {
/** Tokenize string s into an array */ /** Tokenize string s into an array */
public static String[] tokenize(String s) { public static String[] tokenize(String s) {
ArrayList<String> r = new ArrayList<String>(); ArrayList<String> r = new ArrayList<String>();
String remain = s; String remain = s;
int n = 0, pos; int n = 0, pos;
remain = remain.trim(); remain = remain.trim();
while (remain.length() > 0) { while (remain.length() > 0) {
if (remain.startsWith("\"")) { if (remain.startsWith("\"")) {
// Field in quotes // Field in quotes
pos = remain.indexOf('"', 1); pos = remain.indexOf('"', 1);
if (pos == -1) if (pos == -1)
break; break;
r.add(remain.substring(1, pos)); r.add(remain.substring(1, pos));
if (pos + 1 < remain.length()) if (pos + 1 < remain.length())
pos++; pos++;
} else { } else {
// Space-separated field // Space-separated field
pos = remain.indexOf(' ', 0); pos = remain.indexOf(' ', 0);
if (pos == -1) { if (pos == -1) {
r.add(remain); r.add(remain);
remain = ""; remain = "";
} else } else
r.add(remain.substring(0, pos)); r.add(remain.substring(0, pos));
} }
remain = remain.substring(pos + 1); remain = remain.substring(pos + 1);
remain = remain.trim(); remain = remain.trim();
// - is used as a placeholder for empy fields // - is used as a placeholder for empy fields
if (r.get(n).equals("-")) if (r.get(n).equals("-"))
r.set(n, ""); r.set(n, "");
n++; n++;
} }
return r.toArray(new String[0]); return r.toArray(new String[0]);
} }
private final static Pattern ESCAPE_BASIC_XML = Pattern.compile("[&<>]"); private final static Pattern ESCAPE_BASIC_XML = Pattern.compile("[&<>]");
@ -71,47 +71,47 @@ class StringUtil {
* HTML entity code. * HTML entity code.
*/ */
public static String escape(String s) { public static String escape(String s) {
if (ESCAPE_BASIC_XML.matcher(s).find()) { if (ESCAPE_BASIC_XML.matcher(s).find()) {
StringBuilder sb = new StringBuilder(s); StringBuilder sb = new StringBuilder(s);
for (int i = 0; i < sb.length();) { for (int i = 0; i < sb.length();) {
switch (sb.charAt(i)) { switch (sb.charAt(i)) {
case '&': case '&':
sb.replace(i, i + 1, "&amp;"); sb.replace(i, i + 1, "&amp;");
i += "&amp;".length(); i += "&amp;".length();
break; break;
case '<': case '<':
sb.replace(i, i + 1, "&lt;"); sb.replace(i, i + 1, "&lt;");
i += "&lt;".length(); i += "&lt;".length();
break; break;
case '>': case '>':
sb.replace(i, i + 1, "&gt;"); sb.replace(i, i + 1, "&gt;");
i += "&gt;".length(); i += "&gt;".length();
break; break;
default: default:
i++; i++;
} }
} }
return sb.toString(); return sb.toString();
} else } else
return s; return s;
} }
/** /**
* Convert embedded newlines into HTML line breaks * Convert embedded newlines into HTML line breaks
*/ */
public static String htmlNewline(String s) { public static String htmlNewline(String s) {
if (s.indexOf('\n') == -1) if (s.indexOf('\n') == -1)
return s; return s;
StringBuilder sb = new StringBuilder(s); StringBuilder sb = new StringBuilder(s);
for (int i = 0; i < sb.length();) { for (int i = 0; i < sb.length();) {
if (sb.charAt(i) == '\n') { if (sb.charAt(i) == '\n') {
sb.replace(i, i + 1, "<br/>"); sb.replace(i, i + 1, "<br/>");
i += "<br/>".length(); i += "<br/>".length();
} else } else
i++; i++;
} }
return sb.toString(); return sb.toString();
} }
/** /**
@ -119,22 +119,22 @@ class StringUtil {
* characters. * characters.
*/ */
public static String guillemize(Options opt, String s) { public static String guillemize(Options opt, String s) {
StringBuilder r = new StringBuilder(s); StringBuilder r = new StringBuilder(s);
for (int i = 0; i < r.length();) for (int i = 0; i < r.length();)
switch (r.charAt(i)) { switch (r.charAt(i)) {
case '<': case '<':
r.replace(i, i + 1, opt.guilOpen); r.replace(i, i + 1, opt.guilOpen);
i += opt.guilOpen.length(); i += opt.guilOpen.length();
break; break;
case '>': case '>':
r.replace(i, i + 1, opt.guilClose); r.replace(i, i + 1, opt.guilClose);
i += opt.guilClose.length(); i += opt.guilClose.length();
break; break;
default: default:
i++; i++;
break; break;
} }
return r.toString(); return r.toString();
} }
/** /**
@ -144,45 +144,45 @@ class StringUtil {
* @return the wrapped <code>String</code>. * @return the wrapped <code>String</code>.
*/ */
public static String guilWrap(Options opt, String str) { public static String guilWrap(Options opt, String str) {
return opt.guilOpen + str + opt.guilClose; return opt.guilOpen + str + opt.guilClose;
} }
/** Removes the template specs from a class name. */ /** Removes the template specs from a class name. */
public static String removeTemplate(String name) { public static String removeTemplate(String name) {
int openIdx = name.indexOf('<'); int openIdx = name.indexOf('<');
if (openIdx == -1) if (openIdx == -1)
return name; return name;
StringBuilder buf = new StringBuilder(name.length()); StringBuilder buf = new StringBuilder(name.length());
for (int i = 0, depth = 0; i < name.length(); i++) { for (int i = 0, depth = 0; i < name.length(); i++) {
char c = name.charAt(i); char c = name.charAt(i);
if (c == '<') if (c == '<')
depth++; depth++;
else if (c == '>') else if (c == '>')
depth--; depth--;
else if (depth == 0) else if (depth == 0)
buf.append(c); buf.append(c);
} }
return buf.toString(); return buf.toString();
} }
public static String buildRelativePathFromClassNames(String contextPackageName, String classPackageName) { public static String buildRelativePathFromClassNames(String contextPackageName, String classPackageName) {
// path, relative to the root, of the destination class // path, relative to the root, of the destination class
String[] contextClassPath = contextPackageName.split("\\."); String[] contextClassPath = contextPackageName.split("\\.");
String[] currClassPath = classPackageName.split("\\."); String[] currClassPath = classPackageName.split("\\.");
// compute relative path between the context and the destination // compute relative path between the context and the destination
// ... first, compute common part // ... first, compute common part
int i = 0, e = Math.min(contextClassPath.length, currClassPath.length); int i = 0, e = Math.min(contextClassPath.length, currClassPath.length);
while (i < e && contextClassPath[i].equals(currClassPath[i])) while (i < e && contextClassPath[i].equals(currClassPath[i]))
i++; i++;
// ... go up with ".." to reach the common root // ... go up with ".." to reach the common root
StringBuilder buf = new StringBuilder(classPackageName.length()); StringBuilder buf = new StringBuilder(classPackageName.length());
for (int j = i; j < contextClassPath.length; j++) for (int j = i; j < contextClassPath.length; j++)
buf.append("../"); buf.append("../");
// ... go down from the common root to the destination // ... go down from the common root to the destination
for (int j = i; j < currClassPath.length; j++) for (int j = i; j < currClassPath.length; j++)
buf.append(currClassPath[j]).append('/'); // Always use HTML seperators buf.append(currClassPath[j]).append('/'); // Always use HTML seperators
return buf.toString(); return buf.toString();
} }
/** /**
@ -199,24 +199,24 @@ class StringUtil {
* @return Splitting point (Either referring to a dot, or -1) * @return Splitting point (Either referring to a dot, or -1)
*/ */
public static int splitPackageClass(String className) { public static int splitPackageClass(String className) {
int gen = className.indexOf('<'); // Begin before generics. int gen = className.indexOf('<'); // Begin before generics.
int end = gen >= 0 ? gen : className.length(); int end = gen >= 0 ? gen : className.length();
int start = className.lastIndexOf('.', end); int start = className.lastIndexOf('.', end);
// No package name special cases: // No package name special cases:
if (start < 0) if (start < 0)
return gen >= 0 || className.isEmpty() ? -1 // return gen >= 0 || className.isEmpty() ? -1 //
: Character.isLowerCase(className.charAt(0)) ? end : -1; : Character.isLowerCase(className.charAt(0)) ? end : -1;
int split = end; int split = end;
while (true) { while (true) {
if (Character.isLowerCase(className.charAt(start + 1))) if (Character.isLowerCase(className.charAt(start + 1)))
return split; return split;
split = start; // Continue, this looks like a class name. split = start; // Continue, this looks like a class name.
if (start < 0) if (start < 0)
return -1; return -1;
start = className.lastIndexOf('.', start - 1); start = className.lastIndexOf('.', start - 1);
} }
} }
/** /**
* Format a double to a string. * Format a double to a string.
* <p> * <p>
@ -226,6 +226,6 @@ class StringUtil {
* @return Formatted value * @return Formatted value
*/ */
public static String fmt(double val) { public static String fmt(double val) {
return val == Math.round(val) ? Long.toString((long) val) : Double.toString(val); return val == Math.round(val) ? Long.toString((long) val) : Double.toString(val);
} }
} }

View File

@ -6,8 +6,8 @@ import com.sun.javadoc.ClassDoc;
import com.sun.javadoc.RootDoc; import com.sun.javadoc.RootDoc;
/** /**
* Matches every class that extends (directly or indirectly) a class * Matches every class that extends (directly or indirectly) a class matched by
* matched by the regular expression provided. * the regular expression provided.
*/ */
public class SubclassMatcher implements ClassMatcher { public class SubclassMatcher implements ClassMatcher {
@ -15,22 +15,22 @@ public class SubclassMatcher implements ClassMatcher {
protected Pattern pattern; protected Pattern pattern;
public SubclassMatcher(RootDoc root, Pattern pattern) { public SubclassMatcher(RootDoc root, Pattern pattern) {
this.root = root; this.root = root;
this.pattern = pattern; this.pattern = pattern;
} }
public boolean matches(ClassDoc cd) { public boolean matches(ClassDoc cd) {
// if it's the class we're looking for return // if it's the class we're looking for return
if(pattern.matcher(cd.toString()).matches()) if (pattern.matcher(cd.toString()).matches())
return true; return true;
// recurse on supeclass, if available // recurse on supeclass, if available
return cd.superclass() == null ? false : matches(cd.superclass()); return cd.superclass() == null ? false : matches(cd.superclass());
} }
public boolean matches(String name) { public boolean matches(String name) {
ClassDoc cd = root.classNamed(name); ClassDoc cd = root.classNamed(name);
return cd == null ? false : matches(cd); return cd == null ? false : matches(cd);
} }
} }

View File

@ -2,8 +2,10 @@ package org.umlgraph.doclet;
/** /**
* Options for UMLGraph class diagram generation * Options for UMLGraph class diagram generation
*
* @opt operations * @opt operations
* @opt visibility * @opt visibility
* @hidden * @hidden
*/ */
public class UMLOptions {} public class UMLOptions {
}

View File

@ -31,6 +31,7 @@ import com.sun.javadoc.RootDoc;
/** /**
* Doclet API implementation * Doclet API implementation
*
* @depend - - - OptionProvider * @depend - - - OptionProvider
* @depend - - - Options * @depend - - - Options
* @depend - - - View * @depend - - - View
@ -50,139 +51,138 @@ public class UmlGraph {
/** Entry point through javadoc */ /** Entry point through javadoc */
public static boolean start(RootDoc root) throws IOException { public static boolean start(RootDoc root) throws IOException {
Options opt = buildOptions(root); Options opt = buildOptions(root);
root.printNotice("UMLGraph doclet version " + Version.VERSION + " started"); root.printNotice("UMLGraph doclet version " + Version.VERSION + " started");
View[] views = buildViews(opt, root, root); View[] views = buildViews(opt, root, root);
if(views == null) if (views == null)
return false; return false;
if (views.length == 0) if (views.length == 0)
buildGraph(root, opt, null); buildGraph(root, opt, null);
else else
for (int i = 0; i < views.length; i++) for (int i = 0; i < views.length; i++)
buildGraph(root, views[i], null); buildGraph(root, views[i], null);
return true; return true;
} }
public static void main(String args[]) { public static void main(String args[]) {
PrintWriter err = new PrintWriter(System.err); PrintWriter err = new PrintWriter(System.err);
com.sun.tools.javadoc.Main.execute(programName, com.sun.tools.javadoc.Main.execute(programName, err, err, err, docletName, args);
err, err, err, docletName, args);
} }
public static Options getCommentOptions() { public static Options getCommentOptions() {
return commentOptions; return commentOptions;
} }
/** /**
* Creates the base Options object. * Creates the base Options object. This contains both the options specified on
* This contains both the options specified on the command * the command line and the ones specified in the UMLOptions class, if
* line and the ones specified in the UMLOptions class, if available. * available. Also create the globally accessible commentOptions object.
* Also create the globally accessible commentOptions object.
*/ */
public static Options buildOptions(RootDoc root) { public static Options buildOptions(RootDoc root) {
commentOptions = new Options(); commentOptions = new Options();
commentOptions.setOptions(root.options()); commentOptions.setOptions(root.options());
commentOptions.setOptions(findClass(root, "UMLNoteOptions")); commentOptions.setOptions(findClass(root, "UMLNoteOptions"));
commentOptions.shape = Shape.NOTE; commentOptions.shape = Shape.NOTE;
Options opt = new Options(); Options opt = new Options();
opt.setOptions(root.options()); opt.setOptions(root.options());
opt.setOptions(findClass(root, "UMLOptions")); opt.setOptions(findClass(root, "UMLOptions"));
return opt; return opt;
} }
/** Return the ClassDoc for the specified class; null if not found. */ /** Return the ClassDoc for the specified class; null if not found. */
private static ClassDoc findClass(RootDoc root, String name) { private static ClassDoc findClass(RootDoc root, String name) {
ClassDoc[] classes = root.classes(); ClassDoc[] classes = root.classes();
for (ClassDoc cd : classes) for (ClassDoc cd : classes)
if(cd.name().equals(name)) if (cd.name().equals(name))
return cd; return cd;
return null; return null;
} }
/** /**
* Builds and outputs a single graph according to the view overrides * Builds and outputs a single graph according to the view overrides
*/ */
public static void buildGraph(RootDoc root, OptionProvider op, Doc contextDoc) throws IOException { public static void buildGraph(RootDoc root, OptionProvider op, Doc contextDoc) throws IOException {
if(getCommentOptions() == null) if (getCommentOptions() == null)
buildOptions(root); buildOptions(root);
Options opt = op.getGlobalOptions(); Options opt = op.getGlobalOptions();
root.printNotice("Building " + op.getDisplayName()); root.printNotice("Building " + op.getDisplayName());
ClassDoc[] classes = root.classes(); ClassDoc[] classes = root.classes();
ClassGraph c = new ClassGraph(root, op, contextDoc); ClassGraph c = new ClassGraph(root, op, contextDoc);
c.prologue(); c.prologue();
for (ClassDoc cd : classes) for (ClassDoc cd : classes)
c.printClass(cd, true); c.printClass(cd, true);
for (ClassDoc cd : classes) for (ClassDoc cd : classes)
c.printRelations(cd); c.printRelations(cd);
if(opt.inferRelationships) if (opt.inferRelationships)
for (ClassDoc cd : classes) for (ClassDoc cd : classes)
c.printInferredRelations(cd); c.printInferredRelations(cd);
if(opt.inferDependencies) if (opt.inferDependencies)
for (ClassDoc cd : classes) for (ClassDoc cd : classes)
c.printInferredDependencies(cd); c.printInferredDependencies(cd);
c.printExtraClasses(root); c.printExtraClasses(root);
c.epilogue(); c.epilogue();
} }
/** /**
* Builds the views according to the parameters on the command line * Builds the views according to the parameters on the command line
* @param opt The options *
* @param srcRootDoc The RootDoc for the source classes * @param opt The options
* @param viewRootDoc The RootDoc for the view classes (may be * @param srcRootDoc The RootDoc for the source classes
* different, or may be the same as the srcRootDoc) * @param viewRootDoc The RootDoc for the view classes (may be different, or may
* be the same as the srcRootDoc)
*/ */
public static View[] buildViews(Options opt, RootDoc srcRootDoc, RootDoc viewRootDoc) { public static View[] buildViews(Options opt, RootDoc srcRootDoc, RootDoc viewRootDoc) {
if (opt.viewName != null) { if (opt.viewName != null) {
ClassDoc viewClass = viewRootDoc.classNamed(opt.viewName); ClassDoc viewClass = viewRootDoc.classNamed(opt.viewName);
if(viewClass == null) { if (viewClass == null) {
System.out.println("View " + opt.viewName + " not found! Exiting without generating any output."); System.out.println("View " + opt.viewName + " not found! Exiting without generating any output.");
return null; return null;
} }
if(viewClass.tags("view").length == 0) { if (viewClass.tags("view").length == 0) {
System.out.println(viewClass + " is not a view!"); System.out.println(viewClass + " is not a view!");
return null; return null;
} }
if(viewClass.isAbstract()) { if (viewClass.isAbstract()) {
System.out.println(viewClass + " is an abstract view, no output will be generated!"); System.out.println(viewClass + " is an abstract view, no output will be generated!");
return null; return null;
} }
return new View[] { buildView(srcRootDoc, viewClass, opt) }; return new View[] { buildView(srcRootDoc, viewClass, opt) };
} else if (opt.findViews) { } else if (opt.findViews) {
List<View> views = new ArrayList<View>(); List<View> views = new ArrayList<View>();
ClassDoc[] classes = viewRootDoc.classes(); ClassDoc[] classes = viewRootDoc.classes();
// find view classes // find view classes
for (int i = 0; i < classes.length; i++) for (int i = 0; i < classes.length; i++)
if (classes[i].tags("view").length > 0 && !classes[i].isAbstract()) if (classes[i].tags("view").length > 0 && !classes[i].isAbstract())
views.add(buildView(srcRootDoc, classes[i], opt)); views.add(buildView(srcRootDoc, classes[i], opt));
return views.toArray(new View[views.size()]); return views.toArray(new View[views.size()]);
} else } else
return new View[0]; return new View[0];
} }
/** /**
* Builds a view along with its parent views, recursively * Builds a view along with its parent views, recursively
*/ */
private static View buildView(RootDoc root, ClassDoc viewClass, OptionProvider provider) { private static View buildView(RootDoc root, ClassDoc viewClass, OptionProvider provider) {
ClassDoc superClass = viewClass.superclass(); ClassDoc superClass = viewClass.superclass();
if(superClass == null || superClass.tags("view").length == 0) if (superClass == null || superClass.tags("view").length == 0)
return new View(root, viewClass, provider); return new View(root, viewClass, provider);
return new View(root, viewClass, buildView(root, superClass, provider)); return new View(root, viewClass, buildView(root, superClass, provider));
} }
/** Option checking */ /** Option checking */
public static int optionLength(String option) { public static int optionLength(String option) {
return Options.optionLength(option); return Options.optionLength(option);
} }
/** Indicate the language version we support */ /** Indicate the language version we support */
public static LanguageVersion languageVersion() { public static LanguageVersion languageVersion() {
return LanguageVersion.JAVA_1_5; return LanguageVersion.JAVA_1_5;
} }
} }

View File

@ -23,6 +23,7 @@ import com.sun.tools.doclets.standard.Standard;
/** /**
* Chaining doclet that runs the standart Javadoc doclet first, and on success, * Chaining doclet that runs the standart Javadoc doclet first, and on success,
* runs the generation of dot files by UMLGraph * runs the generation of dot files by UMLGraph
*
* @author wolf * @author wolf
* *
* @depend - - - WrappedClassDoc * @depend - - - WrappedClassDoc
@ -30,81 +31,81 @@ import com.sun.tools.doclets.standard.Standard;
*/ */
public class UmlGraphDoc { public class UmlGraphDoc {
/** /**
* Option check, forwards options to the standard doclet, if that one refuses them, * Option check, forwards options to the standard doclet, if that one refuses
* they are sent to UmlGraph * them, they are sent to UmlGraph
*/ */
public static int optionLength(String option) { public static int optionLength(String option) {
int result = Standard.optionLength(option); int result = Standard.optionLength(option);
if (result != 0) if (result != 0)
return result; return result;
else else
return UmlGraph.optionLength(option); return UmlGraph.optionLength(option);
} }
/** /**
* Standard doclet entry point * Standard doclet entry point
*
* @param root * @param root
* @return * @return
*/ */
public static boolean start(RootDoc root) { public static boolean start(RootDoc root) {
root.printNotice("UmlGraphDoc version " + Version.VERSION + ", running the standard doclet"); root.printNotice("UmlGraphDoc version " + Version.VERSION + ", running the standard doclet");
Standard.start(root); Standard.start(root);
root.printNotice("UmlGraphDoc version " + Version.VERSION + ", altering javadocs"); root.printNotice("UmlGraphDoc version " + Version.VERSION + ", altering javadocs");
try { try {
String outputFolder = findOutputPath(root.options()); String outputFolder = findOutputPath(root.options());
Options opt = UmlGraph.buildOptions(root); Options opt = UmlGraph.buildOptions(root);
opt.setOptions(root.options()); opt.setOptions(root.options());
// in javadoc enumerations are always printed // in javadoc enumerations are always printed
opt.showEnumerations = true; opt.showEnumerations = true;
opt.relativeLinksForSourcePackages = true; opt.relativeLinksForSourcePackages = true;
// enable strict matching for hide expressions // enable strict matching for hide expressions
opt.strictMatching = true; opt.strictMatching = true;
// root.printNotice(opt.toString()); // root.printNotice(opt.toString());
generatePackageDiagrams(root, opt, outputFolder); generatePackageDiagrams(root, opt, outputFolder);
generateContextDiagrams(root, opt, outputFolder); generateContextDiagrams(root, opt, outputFolder);
} catch(Throwable t) { } catch (Throwable t) {
root.printWarning("Error: " + t.toString()); root.printWarning("Error: " + t.toString());
t.printStackTrace(); t.printStackTrace();
return false; return false;
} }
return true; return true;
} }
/** /**
* Standand doclet entry * Standand doclet entry
*
* @return * @return
*/ */
public static LanguageVersion languageVersion() { public static LanguageVersion languageVersion() {
return Standard.languageVersion(); return Standard.languageVersion();
} }
/** /**
* Generates the package diagrams for all of the packages that contain classes among those * Generates the package diagrams for all of the packages that contain classes
* returned by RootDoc.class() * among those returned by RootDoc.class()
*/ */
private static void generatePackageDiagrams(RootDoc root, Options opt, String outputFolder) private static void generatePackageDiagrams(RootDoc root, Options opt, String outputFolder) throws IOException {
throws IOException { Set<String> packages = new HashSet<String>();
Set<String> packages = new HashSet<String>(); for (ClassDoc classDoc : root.classes()) {
for (ClassDoc classDoc : root.classes()) { PackageDoc packageDoc = classDoc.containingPackage();
PackageDoc packageDoc = classDoc.containingPackage(); if (!packages.contains(packageDoc.name())) {
if(!packages.contains(packageDoc.name())) { packages.add(packageDoc.name());
packages.add(packageDoc.name()); OptionProvider view = new PackageView(outputFolder, packageDoc, root, opt);
OptionProvider view = new PackageView(outputFolder, packageDoc, root, opt); UmlGraph.buildGraph(root, view, packageDoc);
UmlGraph.buildGraph(root, view, packageDoc); runGraphviz(opt.dotExecutable, outputFolder, packageDoc.name(), packageDoc.name(), root);
runGraphviz(opt.dotExecutable, outputFolder, packageDoc.name(), packageDoc.name(), root); alterHtmlDocs(opt, outputFolder, packageDoc.name(), packageDoc.name(), "package-summary.html",
alterHtmlDocs(opt, outputFolder, packageDoc.name(), packageDoc.name(), Pattern.compile("(</[Hh]2>)|(<h1 title=\"Package\").*"), root);
"package-summary.html", Pattern.compile("(</[Hh]2>)|(<h1 title=\"Package\").*"), root); }
} }
}
} }
/** /**
* Generates the context diagram for a single class * Generates the context diagram for a single class
*/ */
private static void generateContextDiagrams(RootDoc root, Options opt, String outputFolder) private static void generateContextDiagrams(RootDoc root, Options opt, String outputFolder) throws IOException {
throws IOException {
Set<ClassDoc> classDocs = new TreeSet<ClassDoc>(new Comparator<ClassDoc>() { Set<ClassDoc> classDocs = new TreeSet<ClassDoc>(new Comparator<ClassDoc>() {
public int compare(ClassDoc cd1, ClassDoc cd2) { public int compare(ClassDoc cd1, ClassDoc cd2) {
return cd1.name().compareTo(cd2.name()); return cd1.name().compareTo(cd2.name());
@ -113,158 +114,143 @@ public class UmlGraphDoc {
for (ClassDoc classDoc : root.classes()) for (ClassDoc classDoc : root.classes())
classDocs.add(classDoc); classDocs.add(classDoc);
ContextView view = null; ContextView view = null;
for (ClassDoc classDoc : classDocs) { for (ClassDoc classDoc : classDocs) {
try { try {
if(view == null) if (view == null)
view = new ContextView(outputFolder, classDoc, root, opt); view = new ContextView(outputFolder, classDoc, root, opt);
else else
view.setContextCenter(classDoc); view.setContextCenter(classDoc);
UmlGraph.buildGraph(root, view, classDoc); UmlGraph.buildGraph(root, view, classDoc);
runGraphviz(opt.dotExecutable, outputFolder, classDoc.containingPackage().name(), classDoc.name(), root); runGraphviz(opt.dotExecutable, outputFolder, classDoc.containingPackage().name(), classDoc.name(),
alterHtmlDocs(opt, outputFolder, classDoc.containingPackage().name(), classDoc.name(), root);
classDoc.name() + ".html", Pattern.compile(".*(Class|Interface|Enum) " + classDoc.name() + ".*") , root); alterHtmlDocs(opt, outputFolder, classDoc.containingPackage().name(), classDoc.name(),
} catch (Exception e) { classDoc.name() + ".html",
throw new RuntimeException("Error generating " + classDoc.name(), e); Pattern.compile(".*(Class|Interface|Enum) " + classDoc.name() + ".*"), root);
} } catch (Exception e) {
} throw new RuntimeException("Error generating " + classDoc.name(), e);
}
}
} }
/** /**
* Runs Graphviz dot building both a diagram (in png format) and a client side map for it. * Runs Graphviz dot building both a diagram (in png format) and a client side
* map for it.
*/ */
private static void runGraphviz(String dotExecutable, String outputFolder, String packageName, String name, RootDoc root) { private static void runGraphviz(String dotExecutable, String outputFolder, String packageName, String name,
if (dotExecutable == null) { RootDoc root) {
dotExecutable = "dot"; if (dotExecutable == null) {
} dotExecutable = "dot";
File dotFile = new File(outputFolder, packageName.replace(".", "/") + "/" + name + ".dot"); }
File svgFile = new File(outputFolder, packageName.replace(".", "/") + "/" + name + ".svg"); File dotFile = new File(outputFolder, packageName.replace(".", "/") + "/" + name + ".dot");
File svgFile = new File(outputFolder, packageName.replace(".", "/") + "/" + name + ".svg");
try { try {
Process p = Runtime.getRuntime().exec(new String [] { Process p = Runtime.getRuntime().exec(new String[] { dotExecutable, "-Tsvg", "-o",
dotExecutable, svgFile.getAbsolutePath(), dotFile.getAbsolutePath() });
"-Tsvg", BufferedReader reader = new BufferedReader(new InputStreamReader(p.getErrorStream()));
"-o", String line;
svgFile.getAbsolutePath(), while ((line = reader.readLine()) != null)
dotFile.getAbsolutePath() root.printWarning(line);
}); int result = p.waitFor();
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getErrorStream())); if (result != 0)
String line; root.printWarning("Errors running Graphviz on " + dotFile);
while((line = reader.readLine()) != null) } catch (Exception e) {
root.printWarning(line); e.printStackTrace();
int result = p.waitFor(); System.err.println("Ensure that dot is in your path and that its path does not contain spaces");
if (result != 0) }
root.printWarning("Errors running Graphviz on " + dotFile);
} catch (Exception e) {
e.printStackTrace();
System.err.println("Ensure that dot is in your path and that its path does not contain spaces");
}
} }
//Format string for the uml image div tag. // Format string for the uml image div tag.
private static final String UML_DIV_TAG = private static final String UML_DIV_TAG = "<div align=\"center\">"
"<div align=\"center\">" + + "<object width=\"100%%\" height=\"100%%\" type=\"image/svg+xml\" data=\"%1$s.svg\" alt=\"Package class diagram package %1$s\" border=0></object>"
"<object width=\"100%%\" height=\"100%%\" type=\"image/svg+xml\" data=\"%1$s.svg\" alt=\"Package class diagram package %1$s\" border=0></object>" + + "</div>";
"</div>";
private static final String UML_AUTO_SIZED_DIV_TAG = "<div align=\"center\">"
private static final String UML_AUTO_SIZED_DIV_TAG = + "<object type=\"image/svg+xml\" data=\"%1$s.svg\" alt=\"Package class diagram package %1$s\" border=0></object>"
"<div align=\"center\">" + + "</div>";
"<object type=\"image/svg+xml\" data=\"%1$s.svg\" alt=\"Package class diagram package %1$s\" border=0></object>" +
"</div>";
private static final String EXPANDABLE_UML_STYLE = "font-family: Arial,Helvetica,sans-serif;font-size: 1.5em; display: block; width: 250px; height: 20px; background: #009933; padding: 5px; text-align: center; border-radius: 8px; color: white; font-weight: bold;"; private static final String EXPANDABLE_UML_STYLE = "font-family: Arial,Helvetica,sans-serif;font-size: 1.5em; display: block; width: 250px; height: 20px; background: #009933; padding: 5px; text-align: center; border-radius: 8px; color: white; font-weight: bold;";
//Format string for the java script tag. // Format string for the java script tag.
private static final String EXPANDABLE_UML = private static final String EXPANDABLE_UML = "<script type=\"text/javascript\">\n" + "function show() {\n"
"<script type=\"text/javascript\">\n" + + " document.getElementById(\"uml\").innerHTML = \n" + " \'<a style=\"" + EXPANDABLE_UML_STYLE
"function show() {\n" + + "\" href=\"javascript:hide()\">%3$s</a>\' +\n" + " \'%1$s\';\n" + "}\n" + "function hide() {\n"
" document.getElementById(\"uml\").innerHTML = \n" + + " document.getElementById(\"uml\").innerHTML = \n" + " \'<a style=\"" + EXPANDABLE_UML_STYLE
" \'<a style=\"" + EXPANDABLE_UML_STYLE + "\" href=\"javascript:hide()\">%3$s</a>\' +\n" + + "\" href=\"javascript:show()\">%2$s</a>\' ;\n" + "}\n" + "</script>\n" + "<div id=\"uml\" >\n"
" \'%1$s\';\n" + + " <a href=\"javascript:show()\">\n" + " <a style=\"" + EXPANDABLE_UML_STYLE
"}\n" + + "\" href=\"javascript:show()\">%2$s</a> \n" + "</div>";
"function hide() {\n" +
" document.getElementById(\"uml\").innerHTML = \n" +
" \'<a style=\"" + EXPANDABLE_UML_STYLE + "\" href=\"javascript:show()\">%2$s</a>\' ;\n" +
"}\n" +
"</script>\n" +
"<div id=\"uml\" >\n" +
" <a href=\"javascript:show()\">\n" +
" <a style=\"" + EXPANDABLE_UML_STYLE + "\" href=\"javascript:show()\">%2$s</a> \n" +
"</div>";
/** /**
* Takes an HTML file, looks for the first instance of the specified insertion point, and * Takes an HTML file, looks for the first instance of the specified insertion
* inserts the diagram image reference and a client side map in that point. * point, and inserts the diagram image reference and a client side map in that
* point.
*/ */
private static void alterHtmlDocs(Options opt, String outputFolder, String packageName, String className, private static void alterHtmlDocs(Options opt, String outputFolder, String packageName, String className,
String htmlFileName, Pattern insertPointPattern, RootDoc root) throws IOException { String htmlFileName, Pattern insertPointPattern, RootDoc root) throws IOException {
// setup files // setup files
File output = new File(outputFolder, packageName.replace(".", "/")); File output = new File(outputFolder, packageName.replace(".", "/"));
File htmlFile = new File(output, htmlFileName); File htmlFile = new File(output, htmlFileName);
File alteredFile = new File(htmlFile.getAbsolutePath() + ".uml"); File alteredFile = new File(htmlFile.getAbsolutePath() + ".uml");
if (!htmlFile.exists()) { if (!htmlFile.exists()) {
System.err.println("Expected file not found: " + htmlFile.getAbsolutePath()); System.err.println("Expected file not found: " + htmlFile.getAbsolutePath());
return; return;
} }
// parse & rewrite // parse & rewrite
BufferedWriter writer = null; BufferedWriter writer = null;
BufferedReader reader = null; BufferedReader reader = null;
boolean matched = false; boolean matched = false;
try { try {
writer = new BufferedWriter(new OutputStreamWriter(new writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(alteredFile), opt.outputEncoding));
FileOutputStream(alteredFile), opt.outputEncoding)); reader = new BufferedReader(new InputStreamReader(new FileInputStream(htmlFile), opt.outputEncoding));
reader = new BufferedReader(new InputStreamReader(new
FileInputStream(htmlFile), opt.outputEncoding));
String line; String line;
while ((line = reader.readLine()) != null) { while ((line = reader.readLine()) != null) {
writer.write(line); writer.write(line);
writer.newLine(); writer.newLine();
if (!matched && insertPointPattern.matcher(line).matches()) { if (!matched && insertPointPattern.matcher(line).matches()) {
matched = true; matched = true;
String tag;
if (opt.autoSize)
tag = String.format(UML_AUTO_SIZED_DIV_TAG, className);
else
tag = String.format(UML_DIV_TAG, className);
if (opt.collapsibleDiagrams)
tag = String.format(EXPANDABLE_UML, tag, "Show UML class diagram", "Hide UML class diagram");
writer.write("<!-- UML diagram added by UMLGraph version " +
Version.VERSION +
" (http://www.spinellis.gr/umlgraph/) -->");
writer.newLine();
writer.write(tag);
writer.newLine();
}
}
} finally {
if (writer != null)
writer.close();
if (reader != null)
reader.close();
}
// if altered, delete old file and rename new one to the old file name String tag;
if (matched) { if (opt.autoSize)
htmlFile.delete(); tag = String.format(UML_AUTO_SIZED_DIV_TAG, className);
alteredFile.renameTo(htmlFile); else
} else { tag = String.format(UML_DIV_TAG, className);
root.printNotice("Warning, could not find a line that matches the pattern '" + insertPointPattern.pattern() if (opt.collapsibleDiagrams)
+ "'.\n Class diagram reference not inserted"); tag = String.format(EXPANDABLE_UML, tag, "Show UML class diagram", "Hide UML class diagram");
alteredFile.delete(); writer.write("<!-- UML diagram added by UMLGraph version " + Version.VERSION + " (http://www.spinellis.gr/umlgraph/) -->");
} writer.newLine();
writer.write(tag);
writer.newLine();
}
}
} finally {
if (writer != null)
writer.close();
if (reader != null)
reader.close();
}
// if altered, delete old file and rename new one to the old file name
if (matched) {
htmlFile.delete();
alteredFile.renameTo(htmlFile);
} else {
root.printNotice("Warning, could not find a line that matches the pattern '"
+ insertPointPattern.pattern() + "'.\n Class diagram reference not inserted");
alteredFile.delete();
}
} }
/** /**
* Returns the output path specified on the javadoc options * Returns the output path specified on the javadoc options
*/ */
private static String findOutputPath(String[][] options) { private static String findOutputPath(String[][] options) {
for (int i = 0; i < options.length; i++) { for (int i = 0; i < options.length; i++) {
if (options[i][0].equals("-d")) if (options[i][0].equals("-d"))
return options[i][1]; return options[i][1];
} }
return "."; return ".";
} }
} }

View File

@ -1,4 +1,6 @@
/* Automatically generated file */ /* Automatically generated file */
package org.umlgraph.doclet; package org.umlgraph.doclet;
class Version { public static String VERSION = "R5_7_2-60-g0e99a6";}
class Version {
public static String VERSION = "R5_7_2-60-g0e99a6";
}

View File

@ -32,6 +32,7 @@ import com.sun.javadoc.Tag;
* will lead to the creation of a UML class diagram. Multiple views can be * will lead to the creation of a UML class diagram. Multiple views can be
* defined on the same source tree, effectively allowing to create multiple * defined on the same source tree, effectively allowing to create multiple
* class diagram out of it. * class diagram out of it.
*
* @author wolf * @author wolf
* *
* @depend - - - Options * @depend - - - Options
@ -53,121 +54,116 @@ public class View implements OptionProvider {
* Builds a view given the class that contains its definition * Builds a view given the class that contains its definition
*/ */
public View(RootDoc root, ClassDoc c, OptionProvider provider) { public View(RootDoc root, ClassDoc c, OptionProvider provider) {
this.viewDoc = c; this.viewDoc = c;
this.provider = provider; this.provider = provider;
this.root = root; this.root = root;
Tag[] tags = c.tags(); Tag[] tags = c.tags();
ClassMatcher currMatcher = null; ClassMatcher currMatcher = null;
// parse options, get the global ones, and build a map of the // parse options, get the global ones, and build a map of the
// pattern matched overrides // pattern matched overrides
globalOptions = new ArrayList<String[]>(); globalOptions = new ArrayList<String[]>();
for (int i = 0; i < tags.length; i++) { for (int i = 0; i < tags.length; i++) {
if (tags[i].name().equals("@match")) { if (tags[i].name().equals("@match")) {
currMatcher = buildMatcher(tags[i].text()); currMatcher = buildMatcher(tags[i].text());
if(currMatcher != null) { if (currMatcher != null) {
optionOverrides.put(currMatcher, new ArrayList<String[]>()); optionOverrides.put(currMatcher, new ArrayList<String[]>());
} }
} else if (tags[i].name().equals("@opt")) { } else if (tags[i].name().equals("@opt")) {
String[] opts = StringUtil.tokenize(tags[i].text()); String[] opts = StringUtil.tokenize(tags[i].text());
opts[0] = "-" + opts[0]; opts[0] = "-" + opts[0];
if (currMatcher == null) { if (currMatcher == null) {
globalOptions.add(opts); globalOptions.add(opts);
} else { } else {
optionOverrides.get(currMatcher).add(opts); optionOverrides.get(currMatcher).add(opts);
} }
} }
} }
} }
/** /**
* Factory method that builds the appropriate matcher for @match tags * Factory method that builds the appropriate matcher for @match tags
*/ */
private ClassMatcher buildMatcher(String tagText) { private ClassMatcher buildMatcher(String tagText) {
// check there are at least @match <type> and a parameter // check there are at least @match <type> and a parameter
String[] strings = StringUtil.tokenize(tagText); String[] strings = StringUtil.tokenize(tagText);
if (strings.length < 2) { if (strings.length < 2) {
System.err.println("Skipping uncomplete @match tag, type missing: " + tagText + " in view " + viewDoc); System.err.println("Skipping uncomplete @match tag, type missing: " + tagText + " in view " + viewDoc);
return null; return null;
} }
try {
if (strings[0].equals("class")) {
return new PatternMatcher(Pattern.compile(strings[1]));
} else if (strings[0].equals("context")) {
return new ContextMatcher(root, Pattern.compile(strings[1]), getGlobalOptions(),
false);
} else if (strings[0].equals("outgoingContext")) {
return new ContextMatcher(root, Pattern.compile(strings[1]), getGlobalOptions(),
false);
} else if (strings[0].equals("interface")) {
return new InterfaceMatcher(root, Pattern.compile(strings[1]));
} else if (strings[0].equals("subclass")) {
return new SubclassMatcher(root, Pattern.compile(strings[1]));
} else {
System.err.println("Skipping @match tag, unknown match type, in view " + viewDoc);
}
} catch (PatternSyntaxException pse) {
System.err.println("Skipping @match tag due to invalid regular expression '" + tagText
+ "'" + " in view " + viewDoc);
} catch (Exception e) {
System.err.println("Skipping @match tag due to an internal error '" + tagText
+ "'" + " in view " + viewDoc);
e.printStackTrace();
}
return null;
}
// ---------------------------------------------------------------- try {
if (strings[0].equals("class")) {
return new PatternMatcher(Pattern.compile(strings[1]));
} else if (strings[0].equals("context")) {
return new ContextMatcher(root, Pattern.compile(strings[1]), getGlobalOptions(), false);
} else if (strings[0].equals("outgoingContext")) {
return new ContextMatcher(root, Pattern.compile(strings[1]), getGlobalOptions(), false);
} else if (strings[0].equals("interface")) {
return new InterfaceMatcher(root, Pattern.compile(strings[1]));
} else if (strings[0].equals("subclass")) {
return new SubclassMatcher(root, Pattern.compile(strings[1]));
} else {
System.err.println("Skipping @match tag, unknown match type, in view " + viewDoc);
}
} catch (PatternSyntaxException pse) {
System.err.println("Skipping @match tag due to invalid regular expression '" + tagText + "'" + " in view " + viewDoc);
} catch (Exception e) {
System.err.println("Skipping @match tag due to an internal error '" + tagText + "'" + " in view " + viewDoc);
e.printStackTrace();
}
return null;
}
// ----------------------------------------------------------------
// OptionProvider methods // OptionProvider methods
// ---------------------------------------------------------------- // ----------------------------------------------------------------
public Options getOptionsFor(ClassDoc cd) { public Options getOptionsFor(ClassDoc cd) {
Options localOpt = getGlobalOptions(); Options localOpt = getGlobalOptions();
overrideForClass(localOpt, cd); overrideForClass(localOpt, cd);
localOpt.setOptions(cd); localOpt.setOptions(cd);
return localOpt; return localOpt;
} }
public Options getOptionsFor(String name) { public Options getOptionsFor(String name) {
Options localOpt = getGlobalOptions(); Options localOpt = getGlobalOptions();
overrideForClass(localOpt, name); overrideForClass(localOpt, name);
return localOpt; return localOpt;
} }
public Options getGlobalOptions() { public Options getGlobalOptions() {
Options go = provider.getGlobalOptions(); Options go = provider.getGlobalOptions();
boolean outputSet = false; boolean outputSet = false;
for (String[] opts : globalOptions) { for (String[] opts : globalOptions) {
if (Options.matchOption(opts[0], "output")) if (Options.matchOption(opts[0], "output"))
outputSet = true; outputSet = true;
go.setOption(opts); go.setOption(opts);
} }
if (!outputSet) if (!outputSet)
go.setOption(new String[] { "output", viewDoc.name() + ".dot" }); go.setOption(new String[] { "output", viewDoc.name() + ".dot" });
return go; return go;
} }
public void overrideForClass(Options opt, ClassDoc cd) { public void overrideForClass(Options opt, ClassDoc cd) {
provider.overrideForClass(opt, cd); provider.overrideForClass(opt, cd);
for (ClassMatcher cm : optionOverrides.keySet()) for (ClassMatcher cm : optionOverrides.keySet())
if(cm.matches(cd)) if (cm.matches(cd))
for (String[] override : optionOverrides.get(cm)) for (String[] override : optionOverrides.get(cm))
opt.setOption(override); opt.setOption(override);
} }
public void overrideForClass(Options opt, String className) { public void overrideForClass(Options opt, String className) {
provider.overrideForClass(opt, className); provider.overrideForClass(opt, className);
for (ClassMatcher cm : optionOverrides.keySet()) for (ClassMatcher cm : optionOverrides.keySet())
if(cm.matches(className)) if (cm.matches(className))
for (String[] override : optionOverrides.get(cm)) for (String[] override : optionOverrides.get(cm))
opt.setOption(override); opt.setOption(override);
} }
public String getDisplayName() { public String getDisplayName() {
return "view " + viewDoc.name(); return "view " + viewDoc.name();
} }
} }

View File

@ -23,6 +23,7 @@ import com.sun.javadoc.ProgramElementDoc;
/** /**
* Enumerates the possible visibilities in a Java program. For brevity, package * Enumerates the possible visibilities in a Java program. For brevity, package
* private visibility is referred as PACKAGE. * private visibility is referred as PACKAGE.
*
* @author wolf * @author wolf
*/ */
public enum Visibility { public enum Visibility {
@ -31,17 +32,17 @@ public enum Visibility {
final public String symbol; final public String symbol;
private Visibility(String symbol) { private Visibility(String symbol) {
this.symbol = symbol; this.symbol = symbol;
} }
public static Visibility get(ProgramElementDoc doc) { public static Visibility get(ProgramElementDoc doc) {
if (doc.isPrivate()) if (doc.isPrivate())
return PRIVATE; return PRIVATE;
else if (doc.isPackagePrivate()) else if (doc.isPackagePrivate())
return PACKAGE; return PACKAGE;
else if (doc.isProtected()) else if (doc.isProtected())
return PROTECTED; return PROTECTED;
else else
return PUBLIC; return PUBLIC;
} }
} }