spearately count interface implementations
[javainspect.git] / src / main / java / eu / svjatoslav / inspector / java / structure / ClassDescriptor.java
1 /*
2  * JavaInspect - Utility to visualize java software
3  * Copyright (C) 2013, Svjatoslav Agejenko, svjatoslav@svjatoslav.eu
4  * 
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of version 2 of the GNU General Public License
7  * as published by the Free Software Foundation.
8  */
9
10 package eu.svjatoslav.inspector.java.structure;
11
12 import java.lang.reflect.Field;
13 import java.lang.reflect.Method;
14 import java.util.ArrayList;
15 import java.util.List;
16 import java.util.Map;
17 import java.util.SortedSet;
18 import java.util.TreeMap;
19 import java.util.TreeSet;
20
21 /**
22  * Describes single class instance
23  */
24 public class ClassDescriptor implements GraphElement {
25
26         private static final int MAX_REFERECNES_COUNT = 10;
27
28         public final String fullyQualifiedName;
29
30         Map<String, FieldDescriptor> nameToFieldMap = new TreeMap<String, FieldDescriptor>();
31
32         public SortedSet<MethodDescriptor> methods = new TreeSet<MethodDescriptor>();
33
34         /**
35          * Incoming arrows will have this color.
36          */
37         private String distinctiveReferenceColor;
38
39         private String interfaceColor;
40
41         private String superClassColor;
42
43         boolean isEnum;
44
45         boolean isInterface;
46
47         boolean isArray;
48
49         private boolean isShown = true;
50
51         private final ClassGraph classGraph;
52
53         List<ClassDescriptor> interfaces = new ArrayList<ClassDescriptor>();
54
55         ClassDescriptor superClass;
56
57         /**
58          * Amount of field and method references pointing to this class.
59          */
60         private int referencesCount = 0;
61
62         // for interface, counts amount of found implementations
63         private int implementationsCount = 0;
64
65         // counts amount of times this class is extended
66         private int extensionsCount = 0;
67
68         public ClassDescriptor(final Class<? extends Object> clazz,
69                         final ClassGraph dump) {
70                 classGraph = dump;
71
72                 fullyQualifiedName = clazz.getName();
73                 dump.nameToClassMap.put(fullyQualifiedName, this);
74
75                 isArray = clazz.isArray();
76
77                 if (isArray) {
78                         final Class<?> componentType = clazz.getComponentType();
79                         dump.addClass(componentType);
80                 }
81
82                 // System.out.println("class: " + fullyQualifiedName);
83
84                 isEnum = clazz.isEnum();
85
86                 isInterface = clazz.isInterface();
87
88                 if (!isVisible())
89                         return;
90
91                 indexFields(clazz.getDeclaredFields());
92                 indexFields(clazz.getFields());
93
94                 indexMethods(clazz);
95
96                 for (final Class interfaceClass : clazz.getInterfaces()) {
97                         final ClassDescriptor classDescriptor = dump
98                                         .addClass(interfaceClass);
99                         classDescriptor.registerImplementation();
100                         interfaces.add(classDescriptor);
101                 }
102
103                 superClass = dump.addClass(clazz.getSuperclass());
104                 if (superClass != null)
105                         superClass.registerExtension();
106
107         }
108
109         public boolean areReferencesShown() {
110                 return referencesCount <= MAX_REFERECNES_COUNT;
111         }
112
113         public void enlistFieldReferences(final StringBuffer result) {
114                 if (nameToFieldMap.isEmpty())
115                         return;
116
117                 result.append("\n");
118                 result.append("    // field references to other classes\n");
119                 for (final Map.Entry<String, FieldDescriptor> entry : nameToFieldMap
120                                 .entrySet())
121                         result.append(entry.getValue().getDot());
122         }
123
124         public void enlistFields(final StringBuffer result) {
125                 if (nameToFieldMap.isEmpty())
126                         return;
127
128                 result.append("\n");
129                 result.append("    // fields:\n");
130
131                 // enlist fields
132                 for (final Map.Entry<String, FieldDescriptor> entry : nameToFieldMap
133                                 .entrySet())
134                         result.append(entry.getValue().getEmbeddedDot());
135         }
136
137         public void enlistImplementedInterfaces(final StringBuffer result) {
138                 if (interfaces.isEmpty())
139                         return;
140
141                 result.append("\n");
142                 result.append("    // interfaces implemented by class: "
143                                 + fullyQualifiedName + "\n");
144
145                 for (final ClassDescriptor interfaceDescriptor : interfaces) {
146                         if (!interfaceDescriptor.isVisible())
147                                 continue;
148
149                         result.append("    " + interfaceDescriptor.getGraphId() + " -> "
150                                         + getGraphId() + "[style=\"dotted, tapered\", color=\""
151                                         + interfaceDescriptor.getInterfaceColor()
152                                         + "\", penwidth=20, dir=\"forward\"];\n");
153                 }
154         }
155
156         public void enlistMethodReferences(final StringBuffer result) {
157                 if (methods.isEmpty())
158                         return;
159
160                 result.append("\n");
161                 result.append("    // method references to other classes\n");
162                 for (final MethodDescriptor methodDescriptor : methods)
163                         result.append(methodDescriptor.getDot());
164         }
165
166         public void enlistMethods(final StringBuffer result) {
167                 if (methods.isEmpty())
168                         return;
169
170                 result.append("\n");
171                 result.append("    // methods:\n");
172
173                 // enlist methods
174                 for (final MethodDescriptor methodDescriptor : methods)
175                         result.append(methodDescriptor.getEmbeddedDot());
176         }
177
178         public void enlistSuperClass(final StringBuffer result) {
179                 if (superClass == null)
180                         return;
181
182                 if (!superClass.isVisible())
183                         return;
184
185                 result.append("\n");
186                 result.append("    // super class for: " + fullyQualifiedName + "\n");
187
188                 result.append("    " + superClass.getGraphId() + " -> " + getGraphId()
189                                 + "[style=\"tapered\", color=\""
190                                 + superClass.getSuperClassColor()
191                                 + "\", penwidth=10, dir=\"forward\"];\n");
192         }
193
194         public void generateDotHeader(final StringBuffer result) {
195                 result.append("\n");
196                 result.append("// Class: " + fullyQualifiedName + "\n");
197
198                 result.append("    " + getGraphId() + "[label=<<TABLE "
199                                 + getBackgroundColor() + " BORDER=\"" + getBorderWidth()
200                                 + "\" CELLBORDER=\"1\" CELLSPACING=\"0\">\n");
201
202                 result.append("\n");
203                 result.append("    // class descriptor header\n");
204                 result.append("    <TR><TD colspan=\"2\" PORT=\"f0\">"
205                                 + "<FONT POINT-SIZE=\"8.0\" >" + getPackageName()
206                                 + "</FONT><br/>");
207
208                 final String parentClassesName = getParentClassesName();
209                 if (parentClassesName.length() > 0)
210                         result.append("<FONT POINT-SIZE=\"12.0\"><B>" + parentClassesName
211                                         + "</B></FONT><br/>\n");
212
213                 result.append("<FONT POINT-SIZE=\"25.0\"><B>" + getClassName(false)
214                                 + "</B></FONT>" + "</TD></TR>\n");
215         }
216
217         public List<FieldDescriptor> getAllFields() {
218                 final List<FieldDescriptor> result = new ArrayList<FieldDescriptor>();
219
220                 for (final Map.Entry<String, FieldDescriptor> entry : nameToFieldMap
221                                 .entrySet())
222                         result.add(entry.getValue());
223
224                 return result;
225         }
226
227         public String getBackgroundColor() {
228                 String bgColor = "";
229
230                 if (isEnum)
231                         bgColor = "bgcolor=\"navajowhite2\"";
232
233                 if (isInterface)
234                         bgColor = "bgcolor=\"darkslategray1\"";
235
236                 return bgColor;
237         }
238
239         public String getBorderWidth() {
240
241                 if (!areReferencesShown())
242                         return "4";
243                 return "1";
244         }
245
246         public String getClassName(final boolean differentiateArray) {
247                 // this is needed for nested classes
248                 final String actualClassName = fullyQualifiedName.replace('$', '.');
249
250                 final int i = actualClassName.lastIndexOf('.');
251
252                 String result = actualClassName.substring(i + 1);
253
254                 if (isArray)
255                         result = result.substring(0, result.length() - 1);
256
257                 if (differentiateArray)
258                         if (isArray)
259                                 result += " []";
260
261                 // this is needed for nested classes
262                 // result = result.replace('$', '.');
263                 return result;
264         }
265
266         public String getColor() {
267                 if (getDistinctiveColor() == null)
268                         setDistinctiveColor(Utils.getNextDarkColor());
269
270                 return getDistinctiveColor();
271         }
272
273         public String getDistinctiveColor() {
274                 return distinctiveReferenceColor;
275         }
276
277         @Override
278         public String getDot() {
279                 if (!isVisible())
280                         return "";
281
282                 if (isArray)
283                         return "";
284
285                 final StringBuffer result = new StringBuffer();
286
287                 generateDotHeader(result);
288
289                 enlistFields(result);
290
291                 enlistMethods(result);
292
293                 result.append("    </TABLE>>, shape=\"none\"];\n");
294
295                 enlistFieldReferences(result);
296
297                 enlistMethodReferences(result);
298
299                 enlistImplementedInterfaces(result);
300
301                 enlistSuperClass(result);
302
303                 return result.toString();
304         }
305
306         @Override
307         public String getEmbeddedDot() {
308                 return null;
309         }
310
311         @Override
312         public String getGraphId() {
313                 final String result = "class_"
314                                 + fullyQualifiedName.replace('.', '_').replace(";", "")
315                                                 .replace("[L", "").replace('$', '_');
316                 return result;
317         }
318
319         public String getInterfaceColor() {
320                 if (interfaceColor == null)
321                         interfaceColor = Utils.getNextLightColor();
322
323                 return interfaceColor;
324         }
325
326         private int getOutgoingReferencesCount() {
327                 int result = 0;
328
329                 // count method references
330                 for (final MethodDescriptor methodDescriptor : methods)
331                         result += methodDescriptor.getOutsideVisibleReferencesCount();
332
333                 // count field references
334                 for (final FieldDescriptor fieldDescriptor : nameToFieldMap.values())
335                         result += fieldDescriptor.getOutsideVisibleReferencesCount();
336
337                 // count implemented interfaces
338                 for (final ClassDescriptor classDescriptor : interfaces)
339                         if (classDescriptor.isVisible())
340                                 result++;
341
342                 // count superclass
343                 if (superClass != null)
344                         if (superClass.isVisible())
345                                 result++;
346
347                 return result;
348         }
349
350         public String getPackageName() {
351
352                 final int i = fullyQualifiedName.lastIndexOf('.');
353
354                 if (i == -1)
355                         return "";
356
357                 return fullyQualifiedName.substring(0, i).replace("[L", "");
358         }
359
360         // public String getReadableName() {
361         //
362         // // do not print full class name for well known system classes
363         // final String packageName = getPackageName();
364         //
365         // if (packageName.equals("java.util"))
366         // return getClassName();
367         //
368         // if (packageName.equals("java.lang"))
369         // return getClassName();
370         //
371         // return fullyQualifiedName;
372         // }
373
374         public String getParentClassesName() {
375                 int i = fullyQualifiedName.lastIndexOf('.');
376                 final String fullClassName = fullyQualifiedName.substring(i + 1);
377
378                 i = fullClassName.lastIndexOf('$');
379                 if (i == -1)
380                         return "";
381                 final String parentClassesName = fullClassName.substring(0, i);
382                 return parentClassesName.replace('$', '.');
383         }
384
385         public String getSuperClassColor() {
386                 if (superClassColor == null)
387                         superClassColor = Utils.getNextLightColor();
388
389                 return superClassColor;
390         }
391
392         public void hide() {
393                 isShown = false;
394         }
395
396         public void hideClassIfNoReferences() {
397                 if (!isVisible())
398                         return;
399
400                 final int totalReferencesCount = getOutgoingReferencesCount()
401                                 + referencesCount + extensionsCount + implementationsCount;
402
403                 if (totalReferencesCount == 0) {
404                         hide();
405                         return;
406                 }
407
408                 return;
409         }
410
411         public void indexFields(final Field[] fields) {
412                 for (final Field field : fields) {
413                         if (nameToFieldMap.containsKey(field.getName()))
414                                 continue;
415
416                         final FieldDescriptor fieldDescriptor = new FieldDescriptor(field,
417                                         this, classGraph);
418
419                 }
420         }
421
422         private void indexMethods(final Class<? extends Object> clazz) {
423                 final Method[] methods = clazz.getMethods();
424
425                 for (final Method method : methods)
426                         new MethodDescriptor(method, this, classGraph);
427
428         }
429
430         @Override
431         public boolean isVisible() {
432
433                 if (Utils.isSystemDataType(fullyQualifiedName))
434                         return false;
435
436                 if (Utils.isSystemPackage(fullyQualifiedName))
437                         return false;
438
439                 if (!classGraph.getFilter().isClassShown(fullyQualifiedName))
440                         return false;
441
442                 return isShown;
443         }
444
445         /**
446          * Register event when another class is extending this one.
447          */
448         public void registerExtension() {
449                 extensionsCount++;
450         }
451
452         public void registerImplementation() {
453                 implementationsCount++;
454         }
455
456         public void registerReference() {
457                 referencesCount++;
458         }
459
460         public void setDistinctiveColor(final String distinctiveColor) {
461                 distinctiveReferenceColor = distinctiveColor;
462         }
463 }