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