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