e43fe8d3c3d04a630d839bd4b857d98a5763fb8b
[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         protected FieldDescriptor getFieldIgnoreCase(final String fieldToSearch) {
322
323                 for (final String fieldName : nameToFieldMap.keySet())
324                         if (fieldToSearch.equalsIgnoreCase(fieldName))
325                                 return nameToFieldMap.get(fieldName);
326
327                 return null;
328         }
329
330         protected String getFullyQualifiedName() {
331                 return fullyQualifiedName;
332         }
333
334         @Override
335         public String getGraphId() {
336                 final String result = "class_"
337                                 + fullyQualifiedName.replace('.', '_').replace(";", "")
338                                 .replace("[L", "").replace('$', '_');
339                 return result;
340         }
341
342         private String getInterfaceColor() {
343                 if (interfaceColor == null)
344                         interfaceColor = Utils.getNextDarkColor();
345
346                 return interfaceColor;
347         }
348
349         private FieldDescriptor getOrCreateFieldDescriptor(final Field field) {
350
351                 final String fieldName = field.getName();
352
353                 if (nameToFieldMap.containsKey(fieldName))
354                         return nameToFieldMap.get(fieldName);
355
356                 final FieldDescriptor newFieldDescriptor = new FieldDescriptor(this);
357                 nameToFieldMap.put(fieldName, newFieldDescriptor);
358
359                 newFieldDescriptor.analyzeField(field);
360
361                 return newFieldDescriptor;
362         }
363
364         private int getOutgoingReferencesCount() {
365                 int result = 0;
366
367                 // count method references
368                 for (final MethodDescriptor methodDescriptor : methods)
369                         result += methodDescriptor.getOutsideVisibleReferencesCount();
370
371                 // count field references
372                 for (final FieldDescriptor fieldDescriptor : nameToFieldMap.values())
373                         result += fieldDescriptor.getOutsideVisibleReferencesCount();
374
375                 // count implemented interfaces
376                 for (final ClassDescriptor classDescriptor : interfaces)
377                         if (classDescriptor.isVisible())
378                                 result++;
379
380                 // count superclass
381                 if (superClass != null)
382                         if (superClass.isVisible())
383                                 result++;
384
385                 return result;
386         }
387
388         private String getPackageName() {
389
390                 final int i = fullyQualifiedName.lastIndexOf('.');
391
392                 if (i == -1)
393                         return "";
394
395                 return fullyQualifiedName.substring(0, i).replace("[L", "");
396         }
397
398         private String getParentClassesName() {
399                 int i = fullyQualifiedName.lastIndexOf('.');
400                 final String fullClassName = fullyQualifiedName.substring(i + 1);
401
402                 i = fullClassName.lastIndexOf('$');
403                 if (i == -1)
404                         return "";
405                 final String parentClassesName = fullClassName.substring(0, i);
406                 return parentClassesName.replace('$', '.');
407         }
408
409         private String getSuperClassColor() {
410                 if (superClassColor == null)
411                         superClassColor = Utils.getNextLightColor();
412
413                 return superClassColor;
414         }
415
416         /**
417          * Checks if class has field with given name (case is ignored). Returns
418          * <code>true</code> if such field is found.
419          */
420         protected boolean hasFieldIgnoreCase(final String fieldToSearch) {
421
422                 for (final String fieldName : nameToFieldMap.keySet())
423                         if (fieldToSearch.equalsIgnoreCase(fieldName))
424                                 return true;
425
426                 return false;
427         }
428
429         private void hide() {
430                 isShown = false;
431         }
432
433         protected void hideClassIfNoReferences() {
434                 if (!isVisible())
435                         return;
436
437                 final int totalReferencesCount = getOutgoingReferencesCount()
438                                 + referencesCount + extensionsCount + implementationsCount;
439
440                 if (totalReferencesCount == 0) {
441                         hide();
442                         return;
443                 }
444
445                 return;
446         }
447
448         private void indexFields(final Field[] fields) {
449                 for (final Field field : fields)
450                         getOrCreateFieldDescriptor(field);
451         }
452
453         private void indexMethods(final Class<? extends Object> clazz) {
454                 for (final Method method : clazz.getMethods()) {
455                         final MethodDescriptor methodDescriptor = new MethodDescriptor(
456                                         this, method.getName());
457
458                         methods.add(methodDescriptor);
459
460                         methodDescriptor.analyze(method);
461                 }
462
463         }
464
465         @Override
466         public boolean isVisible() {
467
468                 if (Utils.isSystemDataType(fullyQualifiedName))
469                         return false;
470
471                 if (Utils.isSystemPackage(fullyQualifiedName))
472                         return false;
473
474                 if (!getClassGraph().getFilter().isClassShown(fullyQualifiedName))
475                         return false;
476
477                 if (isArray)
478                         if (arrayComponent != null)
479                                 if (Utils.isSystemDataType(arrayComponent.fullyQualifiedName))
480                                         // Do not show references to primitive data types in arrays.
481                                         // That is: there is no point to show reference to byte when
482                                         // we have class with byte array field.
483                                         return false;
484
485                 return isShown;
486         }
487
488         /**
489          * Register event when another class is extending this one.
490          */
491         protected void registerExtension() {
492                 extensionsCount++;
493         }
494
495         protected void registerImplementation() {
496                 implementationsCount++;
497         }
498
499         protected void registerReference() {
500                 referencesCount++;
501         }
502
503 }