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