9f4be8a89da42365a47650605d740eba0134117e
[javainspect.git] / src / main / java / eu / svjatoslav / inspector / java / structure / ClassDescriptor.java
1 /*
2  * JavaInspect - Utility to visualize java software
3  * Copyright (C) 2013, 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 2 of the GNU General Public License
7  * 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.HashMap;
16 import java.util.List;
17 import java.util.Map;
18
19 /**
20  * Describes single class instance
21  */
22 public class ClassDescriptor implements GraphElement {
23
24         private static final int MAX_REFERECNES_COUNT = 10;
25
26         public final String fullyQualifiedName;
27
28         Map<String, FieldDescriptor> nameToFieldMap = new HashMap<String, FieldDescriptor>();
29
30         public List<MethodDescriptor> methods = new ArrayList<MethodDescriptor>();
31
32         /**
33          * Incoming arrows will have this color.
34          */
35         private String distinctiveReferenceColor;
36
37         private String interfaceColor;
38
39         private String superClassColor;
40
41         boolean isEnum;
42
43         boolean isInterface;
44
45         boolean isArray;
46
47         private boolean isShown = true;
48
49         private final ClassGraph dump;
50
51         List<ClassDescriptor> interfaces = new ArrayList<ClassDescriptor>();
52
53         ClassDescriptor superClass;
54
55         /**
56          * Amount of field and method references pointing to this class.
57          */
58         private int referenceCount = 0;
59
60         public ClassDescriptor(final Class<? extends Object> clazz,
61                         final ClassGraph dump) {
62                 this.dump = dump;
63
64                 fullyQualifiedName = clazz.getName();
65                 dump.nameToClassMap.put(fullyQualifiedName, this);
66
67                 isArray = clazz.isArray();
68
69                 if (isArray) {
70                         final Class<?> componentType = clazz.getComponentType();
71                         dump.addClass(componentType);
72                 }
73
74                 // System.out.println("class: " + fullyQualifiedName);
75
76                 isEnum = clazz.isEnum();
77
78                 isInterface = clazz.isInterface();
79
80                 if (!isVisible())
81                         return;
82
83                 indexFields(clazz.getDeclaredFields());
84                 indexFields(clazz.getFields());
85
86                 indexMethods(clazz);
87
88                 for (final Class interfaceClass : clazz.getInterfaces())
89                         interfaces.add(dump.addClass(interfaceClass));
90
91                 superClass = dump.addClass(clazz.getSuperclass());
92         }
93
94         public boolean areReferencesShown() {
95                 return referenceCount <= MAX_REFERECNES_COUNT;
96         }
97
98         public void enlistFieldReferences(final StringBuffer result) {
99                 if (nameToFieldMap.isEmpty())
100                         return;
101
102                 result.append("\n");
103                 result.append("    // field references to other classes\n");
104                 for (final Map.Entry<String, FieldDescriptor> entry : nameToFieldMap
105                                 .entrySet())
106                         result.append(entry.getValue().getDot());
107         }
108
109         public void enlistFields(final StringBuffer result) {
110                 if (nameToFieldMap.isEmpty())
111                         return;
112
113                 result.append("\n");
114                 result.append("    // fields:\n");
115
116                 // enlist fields
117                 for (final Map.Entry<String, FieldDescriptor> entry : nameToFieldMap
118                                 .entrySet())
119                         result.append(entry.getValue().getEmbeddedDot());
120         }
121
122         public void enlistImplementedInterfaces(final StringBuffer result) {
123                 if (interfaces.isEmpty())
124                         return;
125
126                 result.append("\n");
127                 result.append("    // interfaces implemented by class: "
128                                 + fullyQualifiedName + "\n");
129
130                 for (final ClassDescriptor interfaceDescriptor : interfaces) {
131                         if (!interfaceDescriptor.isVisible())
132                                 continue;
133
134                         result.append("    " + interfaceDescriptor.getGraphId() + " -> "
135                                         + getGraphId() + "[style=\"dotted, tapered\", color=\""
136                                         + interfaceDescriptor.getInterfaceColor()
137                                         + "\", penwidth=20, dir=\"forward\"];\n");
138                 }
139         }
140
141         public void enlistMethodReferences(final StringBuffer result) {
142                 if (methods.isEmpty())
143                         return;
144
145                 result.append("\n");
146                 result.append("    // method references to other classes\n");
147                 for (final MethodDescriptor methodDescriptor : methods)
148                         result.append(methodDescriptor.getDot());
149         }
150
151         public void enlistMethods(final StringBuffer result) {
152                 if (methods.isEmpty())
153                         return;
154
155                 result.append("\n");
156                 result.append("    // methods:\n");
157
158                 // enlist methods
159                 for (final MethodDescriptor methodDescriptor : methods)
160                         result.append(methodDescriptor.getEmbeddedDot());
161         }
162
163         public void enlistSuperClass(final StringBuffer result) {
164                 if (superClass == null)
165                         return;
166
167                 if (!superClass.isVisible())
168                         return;
169
170                 result.append("\n");
171                 result.append("    // super class for: " + fullyQualifiedName + "\n");
172
173                 result.append("    " + superClass.getGraphId() + " -> " + getGraphId()
174                                 + "[style=\"tapered\", color=\""
175                                 + superClass.getSuperClassColor()
176                                 + "\", penwidth=10, dir=\"forward\"];\n");
177         }
178
179         public void generateDotHeader(final StringBuffer result) {
180                 result.append("\n");
181                 result.append("// Class: " + fullyQualifiedName + "\n");
182
183                 result.append("    " + getGraphId() + "[label=<<TABLE "
184                                 + getBackgroundColor() + " BORDER=\"" + getBorderWidth()
185                                 + "\" CELLBORDER=\"1\" CELLSPACING=\"0\">\n");
186
187                 result.append("\n");
188                 result.append("    // class descriptor header\n");
189                 result.append("    <TR><TD colspan=\"2\" PORT=\"f0\">"
190                                 + "<FONT POINT-SIZE=\"8.0\" >" + getPackageName()
191                                 + "</FONT><br/>" + "<FONT POINT-SIZE=\"25.0\"><B>"
192                                 + getClassName(false) + "</B></FONT>" + "</TD></TR>\n");
193         }
194
195         public List<FieldDescriptor> getAllFields() {
196                 final List<FieldDescriptor> result = new ArrayList<FieldDescriptor>();
197
198                 for (final Map.Entry<String, FieldDescriptor> entry : nameToFieldMap
199                                 .entrySet())
200                         result.add(entry.getValue());
201
202                 return result;
203         }
204
205         public String getBackgroundColor() {
206                 String bgColor = "";
207
208                 if (isEnum)
209                         bgColor = "bgcolor=\"navajowhite2\"";
210
211                 if (isInterface)
212                         bgColor = "bgcolor=\"darkslategray1\"";
213
214                 return bgColor;
215         }
216
217         public String getBorderWidth() {
218
219                 if (!areReferencesShown())
220                         return "4";
221                 return "1";
222         }
223
224         public String getClassName(final boolean differentiateArray) {
225
226                 final int i = fullyQualifiedName.lastIndexOf('.');
227
228                 String result = fullyQualifiedName.substring(i + 1);
229
230                 if (isArray)
231                         result = result.substring(0, result.length() - 1);
232
233                 if (differentiateArray)
234                         if (isArray)
235                                 result += " []";
236
237                 // this is needed for nested classes
238                 result = result.replace('$', '.');
239                 return result;
240         }
241
242         public String getColor() {
243                 if (getDistinctiveColor() == null)
244                         setDistinctiveColor(Utils.getNextDarkColor());
245
246                 return getDistinctiveColor();
247         }
248
249         public String getDistinctiveColor() {
250                 return distinctiveReferenceColor;
251         }
252
253         @Override
254         public String getDot() {
255                 if (!isVisible())
256                         return "";
257
258                 if (isArray)
259                         return "";
260
261                 final StringBuffer result = new StringBuffer();
262
263                 generateDotHeader(result);
264
265                 enlistFields(result);
266
267                 enlistMethods(result);
268
269                 result.append("    </TABLE>>, shape=\"none\"];\n");
270
271                 enlistFieldReferences(result);
272
273                 enlistMethodReferences(result);
274
275                 enlistImplementedInterfaces(result);
276
277                 enlistSuperClass(result);
278
279                 return result.toString();
280         }
281
282         @Override
283         public String getEmbeddedDot() {
284                 return null;
285         }
286
287         @Override
288         public String getGraphId() {
289                 final String result = "class_"
290                                 + fullyQualifiedName.replace('.', '_').replace(";", "")
291                                                 .replace("[L", "").replace('$', '_');
292                 return result;
293         }
294
295         public String getInterfaceColor() {
296                 if (interfaceColor == null)
297                         interfaceColor = Utils.getNextLightColor();
298
299                 return interfaceColor;
300         }
301
302         public String getPackageName() {
303
304                 final int i = fullyQualifiedName.lastIndexOf('.');
305
306                 if (i == -1)
307                         return "";
308
309                 return fullyQualifiedName.substring(0, i).replace("[L", "");
310         }
311
312         // public String getReadableName() {
313         //
314         // // do not print full class name for well known system classes
315         // final String packageName = getPackageName();
316         //
317         // if (packageName.equals("java.util"))
318         // return getClassName();
319         //
320         // if (packageName.equals("java.lang"))
321         // return getClassName();
322         //
323         // return fullyQualifiedName;
324         // }
325
326         public String getSuperClassColor() {
327                 if (superClassColor == null)
328                         superClassColor = Utils.getNextLightColor();
329
330                 return superClassColor;
331         }
332
333         public void hide() {
334                 isShown = false;
335         }
336
337         public void indexFields(final Field[] fields) {
338                 for (final Field field : fields) {
339                         if (nameToFieldMap.containsKey(field.getName()))
340                                 continue;
341
342                         final FieldDescriptor fieldDescriptor = new FieldDescriptor(field,
343                                         this, dump);
344
345                 }
346         }
347
348         private void indexMethods(final Class<? extends Object> clazz) {
349                 final Method[] methods = clazz.getMethods();
350
351                 for (final Method method : methods)
352                         new MethodDescriptor(method, this, dump);
353
354         }
355
356         @Override
357         public boolean isVisible() {
358
359                 if (Utils.isSystemDataType(fullyQualifiedName))
360                         return false;
361
362                 if (Utils.isSystemPackage(fullyQualifiedName))
363                         return false;
364
365                 return isShown;
366         }
367
368         public void registerReference() {
369                 referenceCount++;
370         }
371
372         public void setDistinctiveColor(final String distinctiveColor) {
373                 distinctiveReferenceColor = distinctiveColor;
374         }
375 }