Source Code Cross Referenced for SerialVersionUIDAdder.java in  » Profiler » JIP » org » objectweb » asm » jip » commons » Java Source Code / Java DocumentationJava Source Code and Java Documentation

Java Source Code / Java Documentation
1. 6.0 JDK Core
2. 6.0 JDK Modules
3. 6.0 JDK Modules com.sun
4. 6.0 JDK Modules com.sun.java
5. 6.0 JDK Modules sun
6. 6.0 JDK Platform
7. Ajax
8. Apache Harmony Java SE
9. Aspect oriented
10. Authentication Authorization
11. Blogger System
12. Build
13. Byte Code
14. Cache
15. Chart
16. Chat
17. Code Analyzer
18. Collaboration
19. Content Management System
20. Database Client
21. Database DBMS
22. Database JDBC Connection Pool
23. Database ORM
24. Development
25. EJB Server geronimo
26. EJB Server GlassFish
27. EJB Server JBoss 4.2.1
28. EJB Server resin 3.1.5
29. ERP CRM Financial
30. ESB
31. Forum
32. GIS
33. Graphic Library
34. Groupware
35. HTML Parser
36. IDE
37. IDE Eclipse
38. IDE Netbeans
39. Installer
40. Internationalization Localization
41. Inversion of Control
42. Issue Tracking
43. J2EE
44. JBoss
45. JMS
46. JMX
47. Library
48. Mail Clients
49. Net
50. Parser
51. PDF
52. Portal
53. Profiler
54. Project Management
55. Report
56. RSS RDF
57. Rule Engine
58. Science
59. Scripting
60. Search Engine
61. Security
62. Sevlet Container
63. Source Control
64. Swing Library
65. Template Engine
66. Test Coverage
67. Testing
68. UML
69. Web Crawler
70. Web Framework
71. Web Mail
72. Web Server
73. Web Services
74. Web Services apache cxf 2.0.1
75. Web Services AXIS2
76. Wiki Engine
77. Workflow Engines
78. XML
79. XML UI
Java
Java Tutorial
Java Open Source
Jar File Download
Java Articles
Java Products
Java by API
Photoshop Tutorials
Maya Tutorials
Flash Tutorials
3ds-Max Tutorials
Illustrator Tutorials
GIMP Tutorials
C# / C Sharp
C# / CSharp Tutorial
C# / CSharp Open Source
ASP.Net
ASP.NET Tutorial
JavaScript DHTML
JavaScript Tutorial
JavaScript Reference
HTML / CSS
HTML CSS Reference
C / ANSI-C
C Tutorial
C++
C++ Tutorial
Ruby
PHP
Python
Python Tutorial
Python Open Source
SQL Server / T-SQL
SQL Server / T-SQL Tutorial
Oracle PL / SQL
Oracle PL/SQL Tutorial
PostgreSQL
SQL / MySQL
MySQL Tutorial
VB.Net
VB.Net Tutorial
Flash / Flex / ActionScript
VBA / Excel / Access / Word
XML
XML Tutorial
Microsoft Office PowerPoint 2007 Tutorial
Microsoft Office Excel 2007 Tutorial
Microsoft Office Word 2007 Tutorial
Java Source Code / Java Documentation » Profiler » JIP » org.objectweb.asm.jip.commons 
Source Cross Referenced  Class Diagram Java Document (Java Doc) 


001:        /***
002:         * ASM: a very small and fast Java bytecode manipulation framework
003:         * Copyright (c) 2000-2005 INRIA, France Telecom
004:         * All rights reserved.
005:         *
006:         * Redistribution and use in source and binary forms, with or without
007:         * modification, are permitted provided that the following conditions
008:         * are met:
009:         * 1. Redistributions of source code must retain the above copyright
010:         *    notice, this list of conditions and the following disclaimer.
011:         * 2. Redistributions in binary form must reproduce the above copyright
012:         *    notice, this list of conditions and the following disclaimer in the
013:         *    documentation and/or other materials provided with the distribution.
014:         * 3. Neither the name of the copyright holders nor the names of its
015:         *    contributors may be used to endorse or promote products derived from
016:         *    this software without specific prior written permission.
017:         *
018:         * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
019:         * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
020:         * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
021:         * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
022:         * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
023:         * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
024:         * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
025:         * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
026:         * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
027:         * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
028:         * THE POSSIBILITY OF SUCH DAMAGE.
029:         */package org.objectweb.asm.jip.commons;
030:
031:        import java.io.ByteArrayOutputStream;
032:        import java.io.DataOutputStream;
033:        import java.io.IOException;
034:        import java.security.MessageDigest;
035:        import java.security.NoSuchAlgorithmException;
036:        import java.util.ArrayList;
037:        import java.util.Arrays;
038:        import java.util.Collection;
039:
040:        import org.objectweb.asm.jip.ClassAdapter;
041:        import org.objectweb.asm.jip.ClassVisitor;
042:        import org.objectweb.asm.jip.FieldVisitor;
043:        import org.objectweb.asm.jip.MethodVisitor;
044:        import org.objectweb.asm.jip.Opcodes;
045:
046:        /**
047:         * A {@link ClassAdapter} that adds a serial version unique identifier to a
048:         * class if missing. Here is typical usage of this class:
049:         * 
050:         * <pre>
051:         *   ClassWriter cw = new ClassWriter(...);
052:         *   ClassVisitor sv = new SerialVersionUIDAdder(cw);
053:         *   ClassVisitor ca = new MyClassAdapter(sv);
054:         *   new ClassReader(orginalClass).accept(ca, false);
055:         * </pre>
056:         * 
057:         * The SVUID algorithm can be found <a href=
058:         * "http://java.sun.com/j2se/1.4.2/docs/guide/serialization/spec/class.html"
059:         * >http://java.sun.com/j2se/1.4.2/docs/guide/serialization/spec/class.html</a>:
060:         * 
061:         * <pre>
062:         * The serialVersionUID is computed using the signature of a stream of bytes
063:         * that reflect the class definition. The National Institute of Standards and
064:         * Technology (NIST) Secure Hash Algorithm (SHA-1) is used to compute a
065:         * signature for the stream. The first two 32-bit quantities are used to form a
066:         * 64-bit hash. A java.lang.DataOutputStream is used to convert primitive data
067:         * types to a sequence of bytes. The values input to the stream are defined by
068:         * the Java Virtual Machine (VM) specification for classes.
069:         *
070:         * The sequence of items in the stream is as follows:
071:         *
072:         * 1. The class name written using UTF encoding.
073:         * 2. The class modifiers written as a 32-bit integer.
074:         * 3. The name of each interface sorted by name written using UTF encoding.
075:         * 4. For each field of the class sorted by field name (except private static
076:         * and private transient fields):
077:         * 1. The name of the field in UTF encoding.
078:         * 2. The modifiers of the field written as a 32-bit integer.
079:         * 3. The descriptor of the field in UTF encoding
080:         * 5. If a class initializer exists, write out the following:
081:         * 1. The name of the method, &lt;clinit&gt;, in UTF encoding.
082:         * 2. The modifier of the method, java.lang.reflect.Modifier.STATIC,
083:         * written as a 32-bit integer.
084:         * 3. The descriptor of the method, ()V, in UTF encoding.
085:         * 6. For each non-private constructor sorted by method name and signature:
086:         * 1. The name of the method, &lt;init&gt;, in UTF encoding.
087:         * 2. The modifiers of the method written as a 32-bit integer.
088:         * 3. The descriptor of the method in UTF encoding.
089:         * 7. For each non-private method sorted by method name and signature:
090:         * 1. The name of the method in UTF encoding.
091:         * 2. The modifiers of the method written as a 32-bit integer.
092:         * 3. The descriptor of the method in UTF encoding.
093:         * 8. The SHA-1 algorithm is executed on the stream of bytes produced by
094:         * DataOutputStream and produces five 32-bit values sha[0..4].
095:         *
096:         * 9. The hash value is assembled from the first and second 32-bit values of 
097:         * the SHA-1 message digest. If the result of the message digest, the five
098:         * 32-bit words H0 H1 H2 H3 H4, is in an array of five int values named 
099:         * sha, the hash value would be computed as follows:
100:         *
101:         * long hash = ((sha[0] &gt;&gt;&gt; 24) &amp; 0xFF) |
102:         * ((sha[0] &gt;&gt;&gt; 16) &amp; 0xFF) &lt;&lt; 8 |
103:         * ((sha[0] &gt;&gt;&gt; 8) &amp; 0xFF) &lt;&lt; 16 |
104:         * ((sha[0] &gt;&gt;&gt; 0) &amp; 0xFF) &lt;&lt; 24 |
105:         * ((sha[1] &gt;&gt;&gt; 24) &amp; 0xFF) &lt;&lt; 32 |
106:         * ((sha[1] &gt;&gt;&gt; 16) &amp; 0xFF) &lt;&lt; 40 |
107:         * ((sha[1] &gt;&gt;&gt; 8) &amp; 0xFF) &lt;&lt; 48 |
108:         * ((sha[1] &gt;&gt;&gt; 0) &amp; 0xFF) &lt;&lt; 56;
109:         * </pre>
110:         * 
111:         * @author Rajendra Inamdar, Vishal Vishnoi
112:         */
113:        public class SerialVersionUIDAdder extends ClassAdapter {
114:
115:            /**
116:             * Flag that indicates if we need to compute SVUID.
117:             */
118:            protected boolean computeSVUID;
119:
120:            /**
121:             * Set to true if the class already has SVUID.
122:             */
123:            protected boolean hasSVUID;
124:
125:            /**
126:             * Classes access flags.
127:             */
128:            protected int access;
129:
130:            /**
131:             * Internal name of the class
132:             */
133:            protected String name;
134:
135:            /**
136:             * Interfaces implemented by the class.
137:             */
138:            protected String[] interfaces;
139:
140:            /**
141:             * Collection of fields. (except private static and private transient
142:             * fields)
143:             */
144:            protected Collection svuidFields;
145:
146:            /**
147:             * Set to true if the class has static initializer.
148:             */
149:            protected boolean hasStaticInitializer;
150:
151:            /**
152:             * Collection of non-private constructors.
153:             */
154:            protected Collection svuidConstructors;
155:
156:            /**
157:             * Collection of non-private methods.
158:             */
159:            protected Collection svuidMethods;
160:
161:            /**
162:             * Creates a new {@link SerialVersionUIDAdder}.
163:             * 
164:             * @param cv a {@link ClassVisitor} to which this visitor will delegate
165:             *        calls.
166:             */
167:            public SerialVersionUIDAdder(final ClassVisitor cv) {
168:                super (cv);
169:                svuidFields = new ArrayList();
170:                svuidConstructors = new ArrayList();
171:                svuidMethods = new ArrayList();
172:            }
173:
174:            // ------------------------------------------------------------------------
175:            // Overriden methods
176:            // ------------------------------------------------------------------------
177:
178:            /*
179:             * Visit class header and get class name, access , and intefraces
180:             * informatoin (step 1,2, and 3) for SVUID computation.
181:             */
182:            public void visit(final int version, final int access,
183:                    final String name, final String signature,
184:                    final String super Name, final String[] interfaces) {
185:                computeSVUID = (access & Opcodes.ACC_INTERFACE) == 0;
186:
187:                if (computeSVUID) {
188:                    this .name = name;
189:                    this .access = access;
190:                    this .interfaces = interfaces;
191:                }
192:
193:                super .visit(version, access, name, signature, super Name,
194:                        interfaces);
195:            }
196:
197:            /*
198:             * Visit the methods and get constructor and method information (step 5 and
199:             * 7). Also determince if there is a class initializer (step 6).
200:             */
201:            public MethodVisitor visitMethod(final int access,
202:                    final String name, final String desc,
203:                    final String signature, final String[] exceptions) {
204:                if (computeSVUID) {
205:                    if (name.equals("<clinit>")) {
206:                        hasStaticInitializer = true;
207:                    }
208:                    /*
209:                     * Remembers non private constructors and methods for SVUID
210:                     * computation For constructor and method modifiers, only the
211:                     * ACC_PUBLIC, ACC_PRIVATE, ACC_PROTECTED, ACC_STATIC, ACC_FINAL,
212:                     * ACC_SYNCHRONIZED, ACC_NATIVE, ACC_ABSTRACT and ACC_STRICT flags
213:                     * are used.
214:                     */
215:                    int mods = access
216:                            & (Opcodes.ACC_PUBLIC | Opcodes.ACC_PRIVATE
217:                                    | Opcodes.ACC_PROTECTED
218:                                    | Opcodes.ACC_STATIC | Opcodes.ACC_FINAL
219:                                    | Opcodes.ACC_SYNCHRONIZED
220:                                    | Opcodes.ACC_NATIVE | Opcodes.ACC_ABSTRACT | Opcodes.ACC_STRICT);
221:
222:                    // all non private methods
223:                    if ((access & Opcodes.ACC_PRIVATE) == 0) {
224:                        if (name.equals("<init>")) {
225:                            svuidConstructors.add(new Item(name, mods, desc));
226:                        } else if (!name.equals("<clinit>")) {
227:                            svuidMethods.add(new Item(name, mods, desc));
228:                        }
229:                    }
230:                }
231:
232:                return cv
233:                        .visitMethod(access, name, desc, signature, exceptions);
234:            }
235:
236:            /*
237:             * Gets class field information for step 4 of the alogrithm. Also determines
238:             * if the class already has a SVUID.
239:             */
240:            public FieldVisitor visitField(final int access, final String name,
241:                    final String desc, final String signature,
242:                    final Object value) {
243:                if (computeSVUID) {
244:                    if (name.equals("serialVersionUID")) {
245:                        // since the class already has SVUID, we won't be computing it.
246:                        computeSVUID = false;
247:                        hasSVUID = true;
248:                    }
249:                    /*
250:                     * Remember field for SVUID computation For field modifiers, only
251:                     * the ACC_PUBLIC, ACC_PRIVATE, ACC_PROTECTED, ACC_STATIC,
252:                     * ACC_FINAL, ACC_VOLATILE, and ACC_TRANSIENT flags are used when
253:                     * computing serialVersionUID values.
254:                     */
255:                    int mods = access
256:                            & (Opcodes.ACC_PUBLIC | Opcodes.ACC_PRIVATE
257:                                    | Opcodes.ACC_PROTECTED
258:                                    | Opcodes.ACC_STATIC | Opcodes.ACC_FINAL
259:                                    | Opcodes.ACC_VOLATILE | Opcodes.ACC_TRANSIENT);
260:
261:                    if (((access & Opcodes.ACC_PRIVATE) == 0)
262:                            || ((access & (Opcodes.ACC_STATIC | Opcodes.ACC_TRANSIENT)) == 0)) {
263:                        svuidFields.add(new Item(name, mods, desc));
264:                    }
265:                }
266:
267:                return super .visitField(access, name, desc, signature, value);
268:            }
269:
270:            /*
271:             * Add the SVUID if class doesn't have one
272:             */
273:            public void visitEnd() {
274:                // compute SVUID and add it to the class
275:                if (computeSVUID && !hasSVUID) {
276:                    try {
277:                        cv.visitField(Opcodes.ACC_FINAL + Opcodes.ACC_STATIC,
278:                                "serialVersionUID", "J", null, new Long(
279:                                        computeSVUID()));
280:                    } catch (Throwable e) {
281:                        throw new RuntimeException(
282:                                "Error while computing SVUID for " + name, e);
283:                    }
284:                }
285:
286:                super .visitEnd();
287:            }
288:
289:            // ------------------------------------------------------------------------
290:            // Utility methods
291:            // ------------------------------------------------------------------------
292:
293:            /**
294:             * Returns the value of SVUID if the class doesn't have one already. Please
295:             * note that 0 is returned if the class already has SVUID, thus use
296:             * <code>isHasSVUID</code> to determine if the class already had an SVUID.
297:             * 
298:             * @return Returns the serial version UID
299:             * @throws IOException
300:             * @throws NoSuchAlgorithmException
301:             */
302:            protected long computeSVUID() throws IOException,
303:                    NoSuchAlgorithmException {
304:                if (hasSVUID) {
305:                    return 0;
306:                }
307:
308:                ByteArrayOutputStream bos = null;
309:                DataOutputStream dos = null;
310:                long svuid = 0;
311:
312:                try {
313:                    bos = new ByteArrayOutputStream();
314:                    dos = new DataOutputStream(bos);
315:
316:                    /*
317:                     * 1. The class name written using UTF encoding.
318:                     */
319:                    dos.writeUTF(name.replace('/', '.'));
320:
321:                    /*
322:                     * 2. The class modifiers written as a 32-bit integer.
323:                     */
324:                    dos
325:                            .writeInt(access
326:                                    & (Opcodes.ACC_PUBLIC | Opcodes.ACC_FINAL
327:                                            | Opcodes.ACC_INTERFACE | Opcodes.ACC_ABSTRACT));
328:
329:                    /*
330:                     * 3. The name of each interface sorted by name written using UTF
331:                     * encoding.
332:                     */
333:                    Arrays.sort(interfaces);
334:                    for (int i = 0; i < interfaces.length; i++) {
335:                        dos.writeUTF(interfaces[i].replace('/', '.'));
336:                    }
337:
338:                    /*
339:                     * 4. For each field of the class sorted by field name (except
340:                     * private static and private transient fields):
341:                     * 
342:                     * 1. The name of the field in UTF encoding. 2. The modifiers of the
343:                     * field written as a 32-bit integer. 3. The descriptor of the field
344:                     * in UTF encoding
345:                     * 
346:                     * Note that field signatutes are not dot separated. Method and
347:                     * constructor signatures are dot separated. Go figure...
348:                     */
349:                    writeItems(svuidFields, dos, false);
350:
351:                    /*
352:                     * 5. If a class initializer exists, write out the following: 1. The
353:                     * name of the method, <clinit>, in UTF encoding. 2. The modifier of
354:                     * the method, java.lang.reflect.Modifier.STATIC, written as a
355:                     * 32-bit integer. 3. The descriptor of the method, ()V, in UTF
356:                     * encoding.
357:                     */
358:                    if (hasStaticInitializer) {
359:                        dos.writeUTF("<clinit>");
360:                        dos.writeInt(Opcodes.ACC_STATIC);
361:                        dos.writeUTF("()V");
362:                    } // if..
363:
364:                    /*
365:                     * 6. For each non-private constructor sorted by method name and
366:                     * signature: 1. The name of the method, <init>, in UTF encoding. 2.
367:                     * The modifiers of the method written as a 32-bit integer. 3. The
368:                     * descriptor of the method in UTF encoding.
369:                     */
370:                    writeItems(svuidConstructors, dos, true);
371:
372:                    /*
373:                     * 7. For each non-private method sorted by method name and
374:                     * signature: 1. The name of the method in UTF encoding. 2. The
375:                     * modifiers of the method written as a 32-bit integer. 3. The
376:                     * descriptor of the method in UTF encoding.
377:                     */
378:                    writeItems(svuidMethods, dos, true);
379:
380:                    dos.flush();
381:
382:                    /*
383:                     * 8. The SHA-1 algorithm is executed on the stream of bytes
384:                     * produced by DataOutputStream and produces five 32-bit values
385:                     * sha[0..4].
386:                     */
387:                    MessageDigest md = MessageDigest.getInstance("SHA");
388:
389:                    /*
390:                     * 9. The hash value is assembled from the first and second 32-bit
391:                     * values of the SHA-1 message digest. If the result of the message
392:                     * digest, the five 32-bit words H0 H1 H2 H3 H4, is in an array of
393:                     * five int values named sha, the hash value would be computed as
394:                     * follows:
395:                     * 
396:                     * long hash = ((sha[0] >>> 24) & 0xFF) | ((sha[0] >>> 16) & 0xFF) <<
397:                     * 8 | ((sha[0] >>> 8) & 0xFF) << 16 | ((sha[0] >>> 0) & 0xFF) <<
398:                     * 24 | ((sha[1] >>> 24) & 0xFF) << 32 | ((sha[1] >>> 16) & 0xFF) <<
399:                     * 40 | ((sha[1] >>> 8) & 0xFF) << 48 | ((sha[1] >>> 0) & 0xFF) <<
400:                     * 56;
401:                     */
402:                    byte[] hashBytes = md.digest(bos.toByteArray());
403:                    for (int i = Math.min(hashBytes.length, 8) - 1; i >= 0; i--) {
404:                        svuid = (svuid << 8) | (hashBytes[i] & 0xFF);
405:                    }
406:                } finally {
407:                    // close the stream (if open)
408:                    if (dos != null) {
409:                        dos.close();
410:                    }
411:                }
412:
413:                return svuid;
414:            }
415:
416:            /**
417:             * Sorts the items in the collection and writes it to the data output stream
418:             * 
419:             * @param itemCollection collection of items
420:             * @param dos a <code>DataOutputStream</code> value
421:             * @param dotted a <code>boolean</code> value
422:             * @exception IOException if an error occurs
423:             */
424:            private void writeItems(final Collection itemCollection,
425:                    final DataOutputStream dos, final boolean dotted)
426:                    throws IOException {
427:                int size = itemCollection.size();
428:                Item items[] = (Item[]) itemCollection.toArray(new Item[size]);
429:                Arrays.sort(items);
430:                for (int i = 0; i < size; i++) {
431:                    dos.writeUTF(items[i].name);
432:                    dos.writeInt(items[i].access);
433:                    dos.writeUTF(dotted ? items[i].desc.replace('/', '.')
434:                            : items[i].desc);
435:                }
436:            }
437:
438:            // ------------------------------------------------------------------------
439:            // Inner classes
440:            // ------------------------------------------------------------------------
441:
442:            static class Item implements  Comparable {
443:
444:                String name;
445:
446:                int access;
447:
448:                String desc;
449:
450:                Item(final String name, final int access, final String desc) {
451:                    this .name = name;
452:                    this .access = access;
453:                    this .desc = desc;
454:                }
455:
456:                public int compareTo(final Object o) {
457:                    Item other = (Item) o;
458:                    int retVal = name.compareTo(other.name);
459:                    if (retVal == 0) {
460:                        retVal = desc.compareTo(other.desc);
461:                    }
462:                    return retVal;
463:                }
464:            }
465:        }
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.