Source Code Cross Referenced for SerialVersionUIDAdder.java in  » Byte-Code » asm » org » objectweb » asm » 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 » Byte Code » asm » org.objectweb.asm.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-2007 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.commons;
030:
031:        import java.io.ByteArrayOutputStream;
032:        import java.io.DataOutput;
033:        import java.io.DataOutputStream;
034:        import java.io.IOException;
035:        import java.security.MessageDigest;
036:        import java.util.ArrayList;
037:        import java.util.Arrays;
038:        import java.util.Collection;
039:
040:        import org.objectweb.asm.ClassAdapter;
041:        import org.objectweb.asm.ClassVisitor;
042:        import org.objectweb.asm.FieldVisitor;
043:        import org.objectweb.asm.MethodVisitor;
044:        import org.objectweb.asm.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 ("<clinit>".equals(name)) {
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 ("<init>".equals(name)) {
225:                            svuidConstructors.add(new Item(name, mods, desc));
226:                        } else if (!"<clinit>".equals(name)) {
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 ("serialVersionUID".equals(name)) {
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:             */
300:            protected long computeSVUID() throws IOException {
301:                ByteArrayOutputStream bos;
302:                DataOutputStream dos = null;
303:                long svuid = 0;
304:
305:                try {
306:                    bos = new ByteArrayOutputStream();
307:                    dos = new DataOutputStream(bos);
308:
309:                    /*
310:                     * 1. The class name written using UTF encoding.
311:                     */
312:                    dos.writeUTF(name.replace('/', '.'));
313:
314:                    /*
315:                     * 2. The class modifiers written as a 32-bit integer.
316:                     */
317:                    dos
318:                            .writeInt(access
319:                                    & (Opcodes.ACC_PUBLIC | Opcodes.ACC_FINAL
320:                                            | Opcodes.ACC_INTERFACE | Opcodes.ACC_ABSTRACT));
321:
322:                    /*
323:                     * 3. The name of each interface sorted by name written using UTF
324:                     * encoding.
325:                     */
326:                    Arrays.sort(interfaces);
327:                    for (int i = 0; i < interfaces.length; i++) {
328:                        dos.writeUTF(interfaces[i].replace('/', '.'));
329:                    }
330:
331:                    /*
332:                     * 4. For each field of the class sorted by field name (except
333:                     * private static and private transient fields):
334:                     * 
335:                     * 1. The name of the field in UTF encoding. 2. The modifiers of the
336:                     * field written as a 32-bit integer. 3. The descriptor of the field
337:                     * in UTF encoding
338:                     * 
339:                     * Note that field signatutes are not dot separated. Method and
340:                     * constructor signatures are dot separated. Go figure...
341:                     */
342:                    writeItems(svuidFields, dos, false);
343:
344:                    /*
345:                     * 5. If a class initializer exists, write out the following: 1. The
346:                     * name of the method, <clinit>, in UTF encoding. 2. The modifier of
347:                     * the method, java.lang.reflect.Modifier.STATIC, written as a
348:                     * 32-bit integer. 3. The descriptor of the method, ()V, in UTF
349:                     * encoding.
350:                     */
351:                    if (hasStaticInitializer) {
352:                        dos.writeUTF("<clinit>");
353:                        dos.writeInt(Opcodes.ACC_STATIC);
354:                        dos.writeUTF("()V");
355:                    } // if..
356:
357:                    /*
358:                     * 6. For each non-private constructor sorted by method name and
359:                     * signature: 1. The name of the method, <init>, in UTF encoding. 2.
360:                     * The modifiers of the method written as a 32-bit integer. 3. The
361:                     * descriptor of the method in UTF encoding.
362:                     */
363:                    writeItems(svuidConstructors, dos, true);
364:
365:                    /*
366:                     * 7. For each non-private method sorted by method name and
367:                     * signature: 1. The name of the method in UTF encoding. 2. The
368:                     * modifiers of the method written as a 32-bit integer. 3. The
369:                     * descriptor of the method in UTF encoding.
370:                     */
371:                    writeItems(svuidMethods, dos, true);
372:
373:                    dos.flush();
374:
375:                    /*
376:                     * 8. The SHA-1 algorithm is executed on the stream of bytes
377:                     * produced by DataOutputStream and produces five 32-bit values
378:                     * sha[0..4].
379:                     */
380:                    byte[] hashBytes = computeSHAdigest(bos.toByteArray());
381:
382:                    /*
383:                     * 9. The hash value is assembled from the first and second 32-bit
384:                     * values of the SHA-1 message digest. If the result of the message
385:                     * digest, the five 32-bit words H0 H1 H2 H3 H4, is in an array of
386:                     * five int values named sha, the hash value would be computed as
387:                     * follows:
388:                     * 
389:                     * long hash = ((sha[0] >>> 24) & 0xFF) | ((sha[0] >>> 16) & 0xFF) <<
390:                     * 8 | ((sha[0] >>> 8) & 0xFF) << 16 | ((sha[0] >>> 0) & 0xFF) <<
391:                     * 24 | ((sha[1] >>> 24) & 0xFF) << 32 | ((sha[1] >>> 16) & 0xFF) <<
392:                     * 40 | ((sha[1] >>> 8) & 0xFF) << 48 | ((sha[1] >>> 0) & 0xFF) <<
393:                     * 56;
394:                     */
395:                    for (int i = Math.min(hashBytes.length, 8) - 1; i >= 0; i--) {
396:                        svuid = (svuid << 8) | (hashBytes[i] & 0xFF);
397:                    }
398:                } finally {
399:                    // close the stream (if open)
400:                    if (dos != null) {
401:                        dos.close();
402:                    }
403:                }
404:
405:                return svuid;
406:            }
407:
408:            /**
409:             * Returns the SHA-1 message digest of the given value.
410:             * 
411:             * @param value the value whose SHA message digest must be computed.
412:             * @return the SHA-1 message digest of the given value.
413:             */
414:            protected byte[] computeSHAdigest(final byte[] value) {
415:                try {
416:                    return MessageDigest.getInstance("SHA").digest(value);
417:                } catch (Exception e) {
418:                    throw new UnsupportedOperationException(e.toString());
419:                }
420:            }
421:
422:            /**
423:             * Sorts the items in the collection and writes it to the data output stream
424:             * 
425:             * @param itemCollection collection of items
426:             * @param dos a <code>DataOutputStream</code> value
427:             * @param dotted a <code>boolean</code> value
428:             * @exception IOException if an error occurs
429:             */
430:            private static void writeItems(final Collection itemCollection,
431:                    final DataOutput dos, final boolean dotted)
432:                    throws IOException {
433:                int size = itemCollection.size();
434:                Item[] items = (Item[]) itemCollection.toArray(new Item[size]);
435:                Arrays.sort(items);
436:                for (int i = 0; i < size; i++) {
437:                    dos.writeUTF(items[i].name);
438:                    dos.writeInt(items[i].access);
439:                    dos.writeUTF(dotted ? items[i].desc.replace('/', '.')
440:                            : items[i].desc);
441:                }
442:            }
443:
444:            // ------------------------------------------------------------------------
445:            // Inner classes
446:            // ------------------------------------------------------------------------
447:
448:            static class Item implements  Comparable {
449:
450:                final String name;
451:
452:                final int access;
453:
454:                final String desc;
455:
456:                Item(final String name, final int access, final String desc) {
457:                    this .name = name;
458:                    this .access = access;
459:                    this .desc = desc;
460:                }
461:
462:                public int compareTo(final Object o) {
463:                    Item other = (Item) o;
464:                    int retVal = name.compareTo(other.name);
465:                    if (retVal == 0) {
466:                        retVal = desc.compareTo(other.desc);
467:                    }
468:                    return retVal;
469:                }
470:            }
471:        }
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.