[jboss-cvs] jbossretro/src/main/org/jboss/ant/tasks/retro ...

Paul Gier pgier at redhat.com
Tue Mar 13 17:30:44 EDT 2007


  User: pgier   
  Date: 07/03/13 17:30:44

  Modified:    src/main/org/jboss/ant/tasks/retro  Weaver.java
  Log:
  JBBUILD-335;  Some minor changes to the interface to allow the maven plugin to call jboss-retro without starting a separate jvm.
  
  Revision  Changes    Path
  1.29      +748 -690  jbossretro/src/main/org/jboss/ant/tasks/retro/Weaver.java
  
  (In the diff below, changes in quantity of whitespace are not shown.)
  
  Index: Weaver.java
  ===================================================================
  RCS file: /cvsroot/jboss/jbossretro/src/main/org/jboss/ant/tasks/retro/Weaver.java,v
  retrieving revision 1.28
  retrieving revision 1.29
  diff -u -b -r1.28 -r1.29
  --- Weaver.java	10 Jan 2007 22:51:14 -0000	1.28
  +++ Weaver.java	13 Mar 2007 21:30:44 -0000	1.29
  @@ -28,8 +28,10 @@
   import java.io.FileInputStream;
   import java.io.FileReader;
   import java.io.IOException;
  +import java.io.InputStream;
   import java.io.PrintWriter;
   import java.lang.annotation.Inherited;
  +import java.net.MalformedURLException;
   import java.net.URL;
   import java.net.URLClassLoader;
   import java.net.URLDecoder;
  @@ -39,6 +41,7 @@
   import java.util.Map;
   import java.util.Set;
   import java.util.StringTokenizer;
  +import java.util.logging.Logger;
   
   import javassist.ClassPool;
   import javassist.CodeConverter;
  @@ -50,6 +53,7 @@
   import javassist.CtNewMethod;
   import javassist.NotFoundException;
   import javassist.bytecode.AnnotationsAttribute;
  +import javassist.bytecode.BadBytecode;
   import javassist.bytecode.ClassFile;
   import javassist.bytecode.ClassFileWriter;
   import javassist.bytecode.CodeAttribute;
  @@ -65,125 +69,167 @@
    *
    * @author <a href="mailto:bill at jboss.org">Bill Burke</a>
    * @author <a href="mailto:adrian at jboss.org">Adrian Brock</a>
  - * @version $Revision: 1.28 $
  + * @version $Revision: 1.29 $
    */
   public class Weaver
   {
  -   private FileFilter classFileFilter = new FileFilter()
  -   {
  -      public boolean accept(File pathname)
  -      {
  -         return pathname.getName().endsWith(".class");
  -      }
  -   };
   
  -   private FileFilter directoryFilter = new FileFilter()
  -   {
  -      public boolean accept(File pathname)
  -      {
  -         return pathname.isDirectory();
  -      }
  -   };
  +   /**
  +    * The paths in the classpath
  +    */
  +   private ArrayList<URL> paths = new ArrayList<URL>();
   
  -   public boolean verbose = false;
  +   /**
  +    * The list of class files to be translated.
  +    */
  +   private ArrayList<File> files = new ArrayList<File>();
   
  -   public boolean suppress = true;
  -   private String outputDir = null;
  +   private String classPathParam = "";
   
  -   public boolean isJarFile(File src)
  -   {
  -      boolean isJarFile = false;
  -      if( src.isFile() )
  -      {
  -         String name = src.getName().toLowerCase();
  -         isJarFile = name.endsWith(".jar") || name.endsWith(".zip");
  -      }
  -      return isJarFile;
  -   }
  +   private static Logger log = Logger.getLogger(Weaver.class.getName());
   
  -   public static void main(String[] args) throws Exception
  -   {
  -      long start = System.currentTimeMillis();
  -      Weaver weaver = new Weaver();
  -      try
  -      {
  -         weaver.weave(args);
  -      }
  -      catch (Exception e)
  -      {
  -         if (weaver.verbose)
  -            throw e;
  -         throw e;
  -      }
  -      System.out.println("Build Successful: " + (System.currentTimeMillis() - start) + " ms");
  -   }
  +   public boolean verbose = false;
   
  -   public void usage()
  -   {
  -      System.err.println("Usage: retro [-cp <classpath>] [-classpath <classpath>] [-verbose] <dir>+");
  -   }
  +   public boolean suppress = true;
   
  -   // Make public and static so that transformers can locate it to do work
  -   // transformers may generate class files and they need to determine
  -   // file locations and such.  This will also be used as a flag to tell
  -   // transformers whether they are in compile or load-time mode.
  -   public static URLClassLoader loader;
  +   private String outputDir = null;
   
  -   public void weave(String[] args) throws Exception
  +   /**
  +    * Parses command line arguments and calls setters.
  +    * @param args
  +    */
  +   public void parseArgs(String[] args)
      {
  -      if (args.length == 0)
  +      if (args.length == 0 || args[0].equalsIgnoreCase("-h") || args[0].equalsIgnoreCase("-help"))
         {
  -         usage();
  -         System.exit(1);
  -         return;
  +         printUsageAndExit();
         }
  -      ArrayList<URL> paths = new ArrayList<URL>();
  -      ArrayList<File> files = new ArrayList<File>();
         for (int i = 0; i < args.length; i++)
         {
            if (args[i].equals("-verbose"))
            {
               verbose = true;
  -            continue;
            }
            else if (args[i].equals("-suppress"))
            {
               suppress = true;
  -            continue;
            }
            else if (args[i].equals("-destdir"))
            {
  -            outputDir = args[i+1];
  +            outputDir = args[i + 1];
               ++i;
  -            continue;
            }
            else if (args[i].equals("-cp") || args[i].equals("-classpath"))
            {
               if (i + 1 > args.length - 1)
               {
  -               usage();
  -               System.exit(1);
  -               return;
  +               printUsageAndExit();
               }
               ++i;
               StringTokenizer tokenizer = new StringTokenizer(args[i], File.pathSeparator);
  +            classPathParam = args[i];
               while (tokenizer.hasMoreTokens())
               {
                  String cpath = tokenizer.nextToken();
                  File f = new File(cpath);
  +               try
  +               {
                  paths.add(f.toURL());
               }
  -            continue;
  +               catch (MalformedURLException mue)
  +               {
  +                  throw new IllegalArgumentException("Malformed URL in classpath param: " + mue);
  +               }
  +            }
            }
            else if (args[i].equals("--SOURCEPATH"))
            {
  +            if (i + 1 > args.length - 1)
  +            {
  +               printUsageAndExit();
  +            }
               addFilesFromSourcePathFile(files, args[++i]);
  -            continue;
            }
  +         else
  +         {
  +            try
  +            {
            File f = new File(args[i]).getCanonicalFile();
            files.add(f);
         }
  +            catch (IOException ioe)
  +            {
  +               throw new IllegalArgumentException("Problem accessing source path: " + ioe);
  +            }
  +         }
  +      }
  +   }
  +
  +   private FileFilter classFileFilter = new FileFilter()
  +   {
  +      public boolean accept(File pathname)
  +      {
  +         return pathname.getName().endsWith(".class");
  +      }
  +   };
  +
  +   private FileFilter directoryFilter = new FileFilter()
  +   {
  +      public boolean accept(File pathname)
  +      {
  +         return pathname.isDirectory();
  +      }
  +   };
  +
  +   /**
  +    * Main method can be called from the command line.
  +    * Usage: Weaver [-cp <classpath>] [-classpath <classpath>] [-verbose] [--SOURCEPATH <source-path-file>] <dir>+
  +    * @param args command line arguments
  +    * @throws Exception if anything goes wrong
  +    */
  +   public static void main(String[] args) throws Exception
  +   {
  +      long start = System.currentTimeMillis();
  +      Weaver weaver = new Weaver();
  +      try
  +      {
  +         weaver.weave(args);
  +      }
  +      catch (Exception e)
  +      {
  +         if (weaver.verbose)
  +            throw e;
  +         throw e;
  +      }
  +      System.out.println("Build Successful: " + (System.currentTimeMillis() - start) + " ms");
  +   }
   
  +   private void printUsageAndExit()
  +   {
  +      usage();
  +      System.exit(1);
  +   }
  +
  +   public void usage()
  +   {
  +      System.err
  +            .println("Usage: Weaver [-cp <classpath>] [-classpath <classpath>] [-verbose] [-destdir <output-dir>] [-suppress] [--SOURCEPATH <source-path-file>] <dir>+");
  +   }
  +
  +   // Make public and static so that transformers can locate it to do work
  +   // transformers may generate class files and they need to determine
  +   // file locations and such.  This will also be used as a flag to tell
  +   // transformers whether they are in compile or load-time mode.
  +   public static URLClassLoader loader;
  +
  +   public void weave(String[] args) throws Exception
  +   {
  +      parseArgs(args);
  +      weave();
  +   }
  +
  +   public void weave() throws Exception
  +   {
         // FIXME class rename configurable
         Map<String, String> classRenames = new HashMap<String, String>();
         classRenames.put("java/lang/annotation/Annotation", "org/jboss/lang/Annotation");
  @@ -291,6 +337,9 @@
            new ClassRedirectEditor()
         };
   
  +      ClassPool pool = ClassPool.getDefault();
  +      pool.appendPathList(classPathParam);
  +
         // FIXME CodeConverter configurable
         CodeConverter[] converters = 
         {
  @@ -302,8 +351,6 @@
   
         Thread.currentThread().setContextClassLoader(loader);
   
  -      ClassPool pool = ClassPool.getDefault();
  -      
         //Add all the classes to compile
         for (File f : files)
         {
  @@ -318,9 +365,11 @@
            else
            {
               if (verbose)
  +            {
                  System.out.println("[retro] " + f + " is neither a java class or a directory");
            }
         }
  +      }
   
         //Compile each class
         for (String className : classesToCompile.keySet())
  @@ -332,17 +381,21 @@
   
      private HashMap<String, CompilerClassInfo> classesToCompile = new HashMap<String, CompilerClassInfo>();
   
  -   private void addDirectory(File dir, ClassPool pool) throws Exception
  +   private void addDirectory(File dir, ClassPool pool) throws IOException, NotFoundException
      {
         File[] classFiles = dir.listFiles(classFileFilter);
         for (File classFile : classFiles)
  +      {
            addFile(classFile, pool);
  +      }
         File[] directories = dir.listFiles(directoryFilter);
         for (File directory : directories)
  +      {
            addDirectory(directory, pool);
      }
  +   }
   
  -   private void addFile(File file, ClassPool pool) throws Exception
  +   private void addFile(File file, ClassPool pool) throws IOException, NotFoundException
      {
         ClassFile cf = createClassFile(file);
         CtClass clazz = pool.get(cf.getName());
  @@ -353,11 +406,16 @@
         classesToCompile.put(className, info);
      }
   
  -   private ClassFile createClassFile(final File file) throws Exception
  +   private ClassFile createClassFile(final File file) throws IOException
      {
  -      DataInputStream is = new DataInputStream(new FileInputStream(file));
  -      ClassFile cf = new ClassFile(is);
  -      is.close();
  +      return createClassFile(new FileInputStream(file));
  +   }
  +
  +   private ClassFile createClassFile(InputStream is) throws IOException
  +   {
  +      DataInputStream dis = new DataInputStream(is);
  +      ClassFile cf = new ClassFile(dis);
  +      dis.close();
         return cf;
      }
   
  @@ -376,26 +434,27 @@
               fileName = reader.readLine();
            }
         }
  -      catch (Exception e)
  +      catch (IOException ioe)
         {
  +         log.warning("Problem reading sourcepath file: " + ioe);
            try
            {
               reader.close();
            }
  -         catch (IOException e1)
  +         catch (IOException ioe1)
            {
  +            throw new RuntimeException(ioe);
            }
  -         throw new RuntimeException(e);
         }
      }
   
  -   public void compileFile(CompilerClassInfo info, Map<String, String> classRenames,
  -      CodeConverter[] converters, ExprEditor[] editors) throws Exception
  +   public void compileFile(CompilerClassInfo info, Map<String, String> classRenames, CodeConverter[] converters,
  +         ExprEditor[] editors) throws Exception
      {
         if (info.isCompiled())
            return;
   
  -      if( verbose )
  +      if (verbose)
       	  System.out.println("[compileFile] " + info.getClassName());
         URL classUrl = loader.getResource(info.getClassName().replace('.', '/') + ".class");
         if (classUrl == null)
  @@ -425,9 +484,8 @@
            System.out.println("[compiled] " + info.getFile());
      }
   
  -   public boolean doWeave(ClassLoader cl, CompilerClassInfo info,
  -      Map classRenames, CodeConverter[] converters, ExprEditor[] editors)
  -      throws Exception
  +   public boolean doWeave(ClassLoader cl, CompilerClassInfo info, Map classRenames, CodeConverter[] converters,
  +         ExprEditor[] editors) throws Exception
      {
         CtClass clazz = info.getClazz();
         ClassFile file = clazz.getClassFile();
  @@ -489,7 +547,7 @@
         }
         
         // Write out the changes
  -      if( outputDir != null )
  +      if (outputDir != null)
            clazz.writeFile(outputDir);
         else
            clazz.writeFile(info.getSrcRoot());
  @@ -505,8 +563,7 @@
       * @param method the method
       * @throws Exception for any error
       */
  -   public static void rewriteLDC(ConstPool constPool, MethodInfo method)
  -      throws Exception
  +   public static void rewriteLDC(ConstPool constPool, MethodInfo method) throws BadBytecode
      {
         CodeAttribute code = method.getCodeAttribute();
         if (code == null)
  @@ -519,11 +576,11 @@
   
            if (op == Opcode.LDC || op == Opcode.LDC_W)
            {
  -            int index0 = iterator.byteAt(index+1);
  +            int index0 = iterator.byteAt(index + 1);
               int constIndex = index0;
               if (op == Opcode.LDC_W)
               {
  -               int index1 = iterator.byteAt(index+2);
  +               int index1 = iterator.byteAt(index + 2);
                  constIndex = (index0 << 8) + index1;
               }
               if (7 == constPool.getTag(constIndex))
  @@ -534,16 +591,18 @@
                  {
                     int b0 = theClassName >>> 8;
                     int b1 = theClassName & 0x0FF;
  -                  iterator.writeByte(b0, index+1);
  -                  iterator.writeByte(b1, index+2);
  +                  iterator.writeByte(b0, index + 1);
  +                  iterator.writeByte(b1, index + 2);
                  }
                  else
                  {
  -                  iterator.writeByte(theClassName, index+1);
  +                  iterator.writeByte(theClassName, index + 1);
                  }
                  int classClass = constPool.addClassInfo("java/lang/Class");
  -               int descriptor = constPool.addMethodrefInfo(classClass, "forName", "(Ljava/lang/String;)Ljava/lang/Class;");
  -               iterator.insert(new byte[] { (byte) Opcode.INVOKESTATIC, (byte) (descriptor >>> 8), (byte) descriptor } );
  +               int descriptor = constPool.addMethodrefInfo(classClass, "forName",
  +                     "(Ljava/lang/String;)Ljava/lang/Class;");
  +               iterator.insert(new byte[]
  +               {(byte) Opcode.INVOKESTATIC, (byte) (descriptor >>> 8), (byte) descriptor});
               }
            }
         }
  @@ -557,8 +616,7 @@
       * @param info the compiler info
       * @throws Exception for any error
       */
  -   public static CtClass rewriteEnum(ClassLoader cl, CompilerClassInfo info)
  -      throws Exception
  +   public static CtClass rewriteEnum(ClassLoader cl, CompilerClassInfo info) throws Exception
      {
         // Get the jdk5 class enum values
         String classname = info.getClassName();
  @@ -573,33 +631,30 @@
         CtClass newEnum = pool.makeClass(classname, baseEnum);
   
         // Create the enum ctor
  -      String ctorSrc = "protected "+newEnum.getSimpleName()+"(String name, int ord){super(name, ord);}";
  +      String ctorSrc = "protected " + newEnum.getSimpleName() + "(String name, int ord){super(name, ord);}";
         CtConstructor ctor = CtNewConstructor.make(ctorSrc, newEnum);
         newEnum.addConstructor(ctor);
   
         // Create the enum constants by iterating over the jdk5 class values
  -      for(Enum e : enums)
  +      for (Enum e : enums)
         {
            String fieldName = e.name();
  -         String fieldSrc = "public static final " + classname + " "
  -            +fieldName + " = new " + classname + "(\""+fieldName
  -            +"\", "+e.ordinal()+");";
  +         String fieldSrc = "public static final " + classname + " " + fieldName + " = new " + classname + "(\""
  +               + fieldName + "\", " + e.ordinal() + ");";
            CtField f2 = CtField.make(fieldSrc, newEnum);
            f2.setName(fieldName);
            newEnum.addField(f2);
         }
   
         // Add a T valueOf(String) method
  -      String valueOfSrc = "public "+newEnum.getName()+" valueOf(String name) {"
  -         + "return org.jboss.lang.Enum.valueOf(getClass(), name);"
  -         +"}";
  +      String valueOfSrc = "public " + newEnum.getName() + " valueOf(String name) {"
  +            + "return org.jboss.lang.Enum.valueOf(getClass(), name);" + "}";
         CtMethod valueOf = CtNewMethod.make(valueOfSrc, newEnum);
         newEnum.addMethod(valueOf);
   
         // Add a T[] values() method
  -      String valuesSrc = "public static final "+newEnum.getName()+"[] values() {"
  -         + "return org.jboss.lang.Enum.values($class);"
  -         +"}";
  +      String valuesSrc = "public static final " + newEnum.getName() + "[] values() {"
  +            + "return org.jboss.lang.Enum.values($class);" + "}";
         CtMethod values = CtNewMethod.make(valuesSrc, newEnum);
         newEnum.addMethod(values);
         return newEnum;
  @@ -613,7 +668,7 @@
            //Only bother with the @Inherited annotation for now, as this is the main thing affecting the container tests
            Annotation[] annotations = visible.getAnnotations();
            boolean changed = false;
  -         for (int i = 0 ; i < annotations.length ; i++)
  +         for (int i = 0; i < annotations.length; i++)
            {
               if (annotations[i].getTypeName().equals(Inherited.class.getName()))
               {
  @@ -631,7 +686,9 @@
      private class CompilerClassInfo
      {
         File file;
  +
         String srcRoot;
  +
         String className;
   
         CtClass clazz;
  @@ -682,6 +739,7 @@
         {
            return clazz;
         }
  +
         public void setClazz(CtClass clazz)
         {
            this.clazz = clazz;
  
  
  



More information about the jboss-cvs-commits mailing list