fixed javadoc issues
[javainspect.git] / src / main / java / eu / svjatoslav / inspector / java / structure / ClassDescriptor.java
1 /*
2  * JavaInspect - Utility to visualize java software
3  * Copyright (C) 2013-2015, 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 3 of the GNU Lesser General Public License
7  * or later 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         private String fullyQualifiedName;
29
30         private final Map<String, FieldDescriptor> nameToFieldMap = new TreeMap<String, FieldDescriptor>();
31
32         private final 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         private ClassDescriptor arrayComponent;
69
70         public ClassDescriptor(final ClassGraph classGraph) {
71                 this.classGraph = classGraph;
72         }
73
74         protected void analyzeClass(final Class<? extends Object> clazz) {
75
76                 fullyQualifiedName = clazz.getName();
77
78                 isArray = clazz.isArray();
79
80                 if (isArray) {
81                         final Class<?> componentType = clazz.getComponentType();
82                         arrayComponent = getClassGraph().getOrCreateClassDescriptor(
83                                         componentType);
84                 }
85
86                 // System.out.println("class: " + fullyQualifiedName);
87
88                 isEnum = clazz.isEnum();
89
90                 isInterface = clazz.isInterface();
91
92                 if (!isVisible())
93                         return;
94
95                 indexFields(clazz.getDeclaredFields());
96                 indexFields(clazz.getFields());
97
98                 indexMethods(clazz);
99
100                 for (final Class interfaceClass : clazz.getInterfaces()) {
101                         final ClassDescriptor interfaceClassDescriptor = getClassGraph()
102                                         .getOrCreateClassDescriptor(interfaceClass);
103                         interfaceClassDescriptor.registerImplementation();
104                         interfaces.add(interfaceClassDescriptor);
105                 }
106
107                 superClass = getClassGraph().getOrCreateClassDescriptor(
108                                 clazz.getSuperclass());
109                 if (superClass != null)
110                         superClass.registerExtension();
111
112         };
113
114         protected boolean areReferencesShown() {
115                 return referencesCount <= MAX_REFERECNES_COUNT;
116         }
117
118         private void enlistFieldReferences(final StringBuffer result) {
119                 if (nameToFieldMap.isEmpty())
120                         return;
121
122                 result.append("\n");
123                 result.append("    // field references to other classes\n");
124                 for (final Map.Entry<String, FieldDescriptor> entry : nameToFieldMap
125                                 .entrySet())
126                         result.append(entry.getValue().getDot());
127         }
128
129         private void enlistFields(final StringBuffer result) {
130                 if (nameToFieldMap.isEmpty())
131                         return;
132
133                 result.append("\n");
134                 result.append("    // fields:\n");
135
136                 // enlist fields
137                 for (final Map.Entry<String, FieldDescriptor> entry : nameToFieldMap
138                                 .entrySet())
139                         result.append(entry.getValue().getEmbeddedDot());
140         }
141
142         private void enlistImplementedInterfaces(final StringBuffer result) {
143                 if (interfaces.isEmpty())
144                         return;
145
146                 result.append("\n");
147                 result.append("    // interfaces implemented by class: "
148                                 + fullyQualifiedName + "\n");
149
150                 for (final ClassDescriptor interfaceDescriptor : interfaces) {
151                         if (!interfaceDescriptor.isVisible())
152                                 continue;
153
154                         if (!interfaceDescriptor.areReferencesShown())
155                                 continue;
156
157                         result.append("    " + interfaceDescriptor.getGraphId() + " -> "
158                                         + getGraphId() + "[style=\"dotted\", color=\""
159                                         + interfaceDescriptor.getInterfaceColor()
160                                         + "\", penwidth=10, dir=\"forward\"];\n");
161                 }
162         }
163
164         private void enlistMethodReferences(final StringBuffer result) {
165                 if (methods.isEmpty())
166                         return;
167
168                 result.append("\n");
169                 result.append("    // method references to other classes\n");
170                 for (final MethodDescriptor methodDescriptor : methods)
171                         result.append(methodDescriptor.getDot());
172         }
173
174         private void enlistMethods(final StringBuffer result) {
175                 if (methods.isEmpty())
176                         return;
177
178                 result.append("\n");
179                 result.append("    // methods:\n");
180
181                 // enlist methods
182                 for (final MethodDescriptor methodDescriptor : methods)
183                         result.append(methodDescriptor.getEmbeddedDot());
184         }
185
186         private void enlistSuperClass(final StringBuffer result) {
187                 if (superClass == null)
188                         return;
189
190                 if (!superClass.isVisible())
191                         return;
192
193                 if (!superClass.areReferencesShown())
194                         return;
195
196                 result.append("\n");
197                 result.append("    // super class for: " + fullyQualifiedName + "\n");
198
199                 result.append("    " + superClass.getGraphId() + " -> " + getGraphId()
200                                 + "[ color=\"" + superClass.getSuperClassColor()
201                                 + "\", penwidth=10, dir=\"forward\"];\n");
202         }
203
204         private void generateDotHeader(final StringBuffer result) {
205                 result.append("\n");
206                 result.append("// Class: " + fullyQualifiedName + "\n");
207
208                 result.append("    " + getGraphId() + "[label=<<TABLE "
209                                 + getBackgroundColor() + " BORDER=\"" + getBorderWidth()
210                                 + "\" CELLBORDER=\"1\" CELLSPACING=\"0\">\n");
211
212                 result.append("\n");
213                 result.append("    // class descriptor header\n");
214                 result.append("    <TR><TD colspan=\"2\" PORT=\"f0\">"
215                                 + "<FONT POINT-SIZE=\"8.0\" >" + getPackageName()
216                                 + "</FONT><br/>");
217
218                 final String parentClassesName = getParentClassesName();
219                 if (parentClassesName.length() > 0)
220                         result.append("<FONT POINT-SIZE=\"12.0\"><B>" + parentClassesName
221                                         + "</B></FONT><br/>\n");
222
223                 result.append("<FONT POINT-SIZE=\"25.0\"><B>" + getClassName(false)
224                                 + "</B></FONT>" + "</TD></TR>\n");
225         }
226
227         private 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         private String getBorderWidth() {
240
241                 if (!areReferencesShown())
242                         return "4";
243                 return "1";
244         }
245
246         protected ClassGraph getClassGraph() {
247                 return classGraph;
248         }
249
250         protected String getClassName(final boolean differentiateArray) {
251                 // this is needed for nested classes
252                 final String actualClassName = fullyQualifiedName.replace('$', '.');
253
254                 String result;
255                 if (isArray) {
256                         // for arrays use array component instead of array class name
257                         result = arrayComponent.fullyQualifiedName;
258                         if (result.contains(".")) {
259                                 final int i = result.lastIndexOf('.');
260                                 result = result.substring(i + 1);
261                         }
262                 } else {
263                         final int i = actualClassName.lastIndexOf('.');
264                         result = actualClassName.substring(i + 1);
265                 }
266
267                 if (differentiateArray)
268                         if (isArray)
269                                 result += " []";
270
271                 // this is needed for nested classes
272                 // result = result.replace('$', '.');
273                 return result;
274         }
275
276         protected String getColor() {
277                 if (distinctiveReferenceColor == null)
278                         distinctiveReferenceColor = Utils.getNextDarkColor();
279
280                 return distinctiveReferenceColor;
281         }
282
283         @Override
284         public String getDot() {
285                 if (!isVisible())
286                         return "";
287
288                 if (isArray)
289                         return "";
290
291                 final StringBuffer result = new StringBuffer();
292
293                 generateDotHeader(result);
294
295                 enlistFields(result);
296
297                 enlistMethods(result);
298
299                 result.append("    </TABLE>>, shape=\"none\"];\n");
300
301                 enlistFieldReferences(result);
302
303                 enlistMethodReferences(result);
304
305                 enlistImplementedInterfaces(result);
306
307                 enlistSuperClass(result);
308
309                 return result.toString();
310         }
311
312         @Override
313         public String getEmbeddedDot() {
314                 return null;
315         }
316
317         /**
318          * Returns field with given name (case is ignored). Or <code>null</code> if
319          * field is not found.
320          *
321          * @param fieldToSearch
322          *            field name (case is ignored)
323          * @return field matching given name
324          */
325         protected FieldDescriptor getFieldIgnoreCase(final String fieldToSearch) {
326
327                 for (final String fieldName : nameToFieldMap.keySet())
328                         if (fieldToSearch.equalsIgnoreCase(fieldName))
329                                 return nameToFieldMap.get(fieldName);
330
331                 return null;
332         }
333
334         protected String getFullyQualifiedName() {
335                 return fullyQualifiedName;
336         }
337
338         @Override
339         public String getGraphId() {
340                 final String result = "class_"
341                                 + fullyQualifiedName.replace('.', '_').replace(";", "")
342                                                 .replace("[L", "").replace('$', '_');
343                 return result;
344         }
345
346         private String getInterfaceColor() {
347                 if (interfaceColor == null)
348                         interfaceColor = Utils.getNextDarkColor();
349
350                 return interfaceColor;
351         }
352
353         private FieldDescriptor getOrCreateFieldDescriptor(final Field field) {
354
355                 final String fieldName = field.getName();
356
357                 if (nameToFieldMap.containsKey(fieldName))
358                         return nameToFieldMap.get(fieldName);
359
360                 final FieldDescriptor newFieldDescriptor = new FieldDescriptor(this);
361                 nameToFieldMap.put(fieldName, newFieldDescriptor);
362
363                 newFieldDescriptor.analyzeField(field);
364
365                 return newFieldDescriptor;
366         }
367
368         private int getOutgoingReferencesCount() {
369                 int result = 0;
370
371                 // count method references
372                 for (final MethodDescriptor methodDescriptor : methods)
373                         result += methodDescriptor.getOutsideVisibleReferencesCount();
374
375                 // count field references
376                 for (final FieldDescriptor fieldDescriptor : nameToFieldMap.values())
377                         result += fieldDescriptor.getOutsideVisibleReferencesCount();
378
379                 // count implemented interfaces
380                 for (final ClassDescriptor classDescriptor : interfaces)
381                         if (classDescriptor.isVisible())
382                                 result++;
383
384                 // count superclass
385                 if (superClass != null)
386                         if (superClass.isVisible())
387                                 result++;
388
389                 return result;
390         }
391
392         private String getPackageName() {
393
394                 final int i = fullyQualifiedName.lastIndexOf('.');
395
396                 if (i == -1)
397                         return "";
398
399                 return fullyQualifiedName.substring(0, i).replace("[L", "");
400         }
401
402         private String getParentClassesName() {
403                 int i = fullyQualifiedName.lastIndexOf('.');
404                 final String fullClassName = fullyQualifiedName.substring(i + 1);
405
406                 i = fullClassName.lastIndexOf('$');
407                 if (i == -1)
408                         return "";
409                 final String parentClassesName = fullClassName.substring(0, i);
410                 return parentClassesName.replace('$', '.');
411         }
412
413         private String getSuperClassColor() {
414                 if (superClassColor == null)
415                         superClassColor = Utils.getNextLightColor();
416
417                 return superClassColor;
418         }
419
420         /**
421          * Checks if class has field with given name (case is ignored). Returns
422          * <code>true</code> if such field is found.
423          *
424          * @param fieldToSearch
425          *            field to search for (case is ignored)
426          *
427          * @return <code>true</code> if field is found.
428          */
429         protected boolean hasFieldIgnoreCase(final String fieldToSearch) {
430
431                 for (final String fieldName : nameToFieldMap.keySet())
432                         if (fieldToSearch.equalsIgnoreCase(fieldName))
433                                 return true;
434
435                 return false;
436         }
437
438         private void hide() {
439                 isShown = false;
440         }
441
442         protected void hideClassIfNoReferences() {
443                 if (!isVisible())
444                         return;
445
446                 final int totalReferencesCount = getOutgoingReferencesCount()
447                                 + referencesCount + extensionsCount + implementationsCount;
448
449                 if (totalReferencesCount == 0) {
450                         hide();
451                         return;
452                 }
453
454                 return;
455         }
456
457         private void indexFields(final Field[] fields) {
458                 for (final Field field : fields)
459                         getOrCreateFieldDescriptor(field);
460         }
461
462         private void indexMethods(final Class<? extends Object> clazz) {
463                 for (final Method method : clazz.getMethods()) {
464                         final MethodDescriptor methodDescriptor = new MethodDescriptor(
465                                         this, method.getName());
466
467                         methods.add(methodDescriptor);
468
469                         methodDescriptor.analyze(method);
470                 }
471
472         }
473
474         @Override
475         public boolean isVisible() {
476
477                 if (Utils.isSystemDataType(fullyQualifiedName))
478                         return false;
479
480                 if (Utils.isSystemPackage(fullyQualifiedName))
481                         return false;
482
483                 if (!getClassGraph().isClassShown(fullyQualifiedName))
484                         return false;
485
486                 if (isArray)
487                         if (arrayComponent != null)
488                                 if (Utils.isSystemDataType(arrayComponent.fullyQualifiedName))
489                                         // Do not show references to primitive data types in arrays.
490                                         // That is: there is no point to show reference to byte when
491                                         // we have class with byte array field.
492                                         return false;
493
494                 return isShown;
495         }
496
497         /**
498          * Register event when another class is extending this one.
499          */
500         protected void registerExtension() {
501                 extensionsCount++;
502         }
503
504         protected void registerImplementation() {
505                 implementationsCount++;
506         }
507
508         protected void registerReference() {
509                 referencesCount++;
510         }
511
512 }