You are viewing a plain text version of this content. The canonical link for it is here.
Posted to dev@tomcat.apache.org by re...@apache.org on 2004/08/17 01:48:36 UTC

cvs commit: jakarta-tomcat-jasper/jasper2/src/share/org/apache/jasper JspCompilationContext.java

remm        2004/08/16 16:48:36

  Modified:    jasper2/src/share/org/apache/jasper/compiler
                        ErrorDispatcher.java Compiler.java
               jasper2/src/share/org/apache/jasper
                        JspCompilationContext.java
  Added:       jasper2/src/share/org/apache/jasper/compiler
                        AntCompiler.java JDTCompiler.java
  Log:
  - Add JDT support.
  - The plugin system is quite bad but works (I did this on the train, which was very late, but still not late enough
    for me to come up with something better): if JDT isn't there, use Ant.
  - Error mapping is implemented with JDT.
  - JDT is about twice as fast as javac, while being less than 1MB, and loading source dependencies from the
    context classloader (this should help a lot for servers with disk trashing during compilation; of course, the code
    generation is a very expensive step as well). This will allow Tomcat to run on a JRE only as well.
  - I didn't test the speed of the generated bytecode yet against the javac generated bytecode for the same class
    (Jikes used to be bad at that).
  - The code was stolen from Cocoon (which removed their author tags so I can't credit anyone for the good code :( ).
  
  Revision  Changes    Path
  1.22      +72 -56    jakarta-tomcat-jasper/jasper2/src/share/org/apache/jasper/compiler/ErrorDispatcher.java
  
  Index: ErrorDispatcher.java
  ===================================================================
  RCS file: /home/cvs/jakarta-tomcat-jasper/jasper2/src/share/org/apache/jasper/compiler/ErrorDispatcher.java,v
  retrieving revision 1.21
  retrieving revision 1.22
  diff -u -r1.21 -r1.22
  --- ErrorDispatcher.java	13 Jul 2004 18:40:08 -0000	1.21
  +++ ErrorDispatcher.java	16 Aug 2004 23:48:35 -0000	1.22
  @@ -432,13 +432,13 @@
                                   String errMsg, String fname, Node.Nodes page)
   	        throws IOException, JasperException {
   
  -	Vector errVec = new Vector();
  -	StringBuffer errMsgBuf = null;
  -	int lineNum = -1;
  +        Vector errVec = new Vector();
  +        StringBuffer errMsgBuf = null;
  +        int lineNum = -1;
           JavacErrorDetail javacError = null;
  -
  +        
           BufferedReader reader = new BufferedReader(new StringReader(errMsg));
  -
  +        
           /*
            * Parse compilation errors. Each compilation error consists of a file
            * path and error line number, followed by a number of lines describing
  @@ -446,82 +446,98 @@
            */
           String line = null;
           while ((line = reader.readLine()) != null) {
  -
  +            
               /*
  -	     * Error line number is delimited by set of colons.
  -	     * Ignore colon following drive letter on Windows (fromIndex = 2).
  -	     * XXX Handle deprecation warnings that don't have line info
  -	     */
  +             * Error line number is delimited by set of colons.
  +             * Ignore colon following drive letter on Windows (fromIndex = 2).
  +             * XXX Handle deprecation warnings that don't have line info
  +             */
               int beginColon = line.indexOf(':', 2); 
               int endColon = line.indexOf(':', beginColon + 1);
               if ((beginColon >= 0) && (endColon >= 0)) {
                   if (javacError != null) {
                       // add previous error to error vector
                       errVec.add(javacError);
  -		}
  -
  -		String lineNumStr = line.substring(beginColon + 1, endColon);
  +                }
  +                
  +                String lineNumStr = line.substring(beginColon + 1, endColon);
                   try {
                       lineNum = Integer.parseInt(lineNumStr);
                   } catch (NumberFormatException e) {
                       // XXX
                   }
  -
  +                
                   errMsgBuf = new StringBuffer();
  -
  -                // Attempt to map javac error line number to line in JSP page
  -		ErrorVisitor errVisitor = new ErrorVisitor(lineNum);
  -		page.visit(errVisitor);
  -                Node errNode = errVisitor.getJspSourceNode();
  -                if ((errNode != null) && (errNode.getStart() != null)) {
  -                    javacError = new JavacErrorDetail(
  -                                            fname,
  -                                            lineNum,
  -                                            errNode.getStart().getFile(),
  -                                            errNode.getStart().getLineNumber(),
  -                                            errMsgBuf);
  -                } else {
  -                    /*
  -                     * javac error line number cannot be mapped to JSP page
  -                     * line number. For example, this is the case if a 
  -                     * scriptlet is missing a closing brace, which causes
  -                     * havoc with the try-catch-finally block that the code
  -                     * generator places around all generated code: As a result
  -                     * of this, the javac error line numbers will be outside
  -                     * the range of begin and end java line numbers that were
  -                     * generated for the scriptlet, and therefore cannot be
  -                     * mapped to the start line number of the scriptlet in the
  -                     * JSP page.
  -                     * Include just the javac error info in the error detail.
  -                     */
  -                    javacError = new JavacErrorDetail(
  -                                            fname,
  -                                            lineNum,
  -                                            errMsgBuf);
  -                }
  +                
  +                javacError = createJavacError(fname, page, errMsgBuf, lineNum);
               }
  -
  +            
               // Ignore messages preceding first error
               if (errMsgBuf != null) {
                   errMsgBuf.append(line);
                   errMsgBuf.append("\n");
               }
           }
  -
  +        
           // Add last error to error vector
           if (javacError != null) {
               errVec.add(javacError);
           } 
  -
  +        
           reader.close();
  -
  -	JavacErrorDetail[] errDetails = null;
  -	if (errVec.size() > 0) {
  -	    errDetails = new JavacErrorDetail[errVec.size()];
  -	    errVec.copyInto(errDetails);
  -	}
  -
  -	return errDetails;
  +        
  +        JavacErrorDetail[] errDetails = null;
  +        if (errVec.size() > 0) {
  +            errDetails = new JavacErrorDetail[errVec.size()];
  +            errVec.copyInto(errDetails);
  +        }
  +        
  +        return errDetails;
  +    }
  +
  +
  +    /**
  +     * @param fname
  +     * @param page
  +     * @param errMsgBuf
  +     * @param lineNum
  +     * @return
  +     * @throws JasperException
  +     */
  +    public static JavacErrorDetail createJavacError(String fname, Node.Nodes page, 
  +            StringBuffer errMsgBuf, int lineNum) throws JasperException {
  +        JavacErrorDetail javacError;
  +        // Attempt to map javac error line number to line in JSP page
  +        ErrorVisitor errVisitor = new ErrorVisitor(lineNum);
  +        page.visit(errVisitor);
  +        Node errNode = errVisitor.getJspSourceNode();
  +        if ((errNode != null) && (errNode.getStart() != null)) {
  +            javacError = new JavacErrorDetail(
  +                    fname,
  +                    lineNum,
  +                    errNode.getStart().getFile(),
  +                    errNode.getStart().getLineNumber(),
  +                    errMsgBuf);
  +        } else {
  +            /*
  +             * javac error line number cannot be mapped to JSP page
  +             * line number. For example, this is the case if a 
  +             * scriptlet is missing a closing brace, which causes
  +             * havoc with the try-catch-finally block that the code
  +             * generator places around all generated code: As a result
  +             * of this, the javac error line numbers will be outside
  +             * the range of begin and end java line numbers that were
  +             * generated for the scriptlet, and therefore cannot be
  +             * mapped to the start line number of the scriptlet in the
  +             * JSP page.
  +             * Include just the javac error info in the error detail.
  +             */
  +            javacError = new JavacErrorDetail(
  +                    fname,
  +                    lineNum,
  +                    errMsgBuf);
  +        }
  +        return javacError;
       }
   
   
  
  
  
  1.92      +12 -207   jakarta-tomcat-jasper/jasper2/src/share/org/apache/jasper/compiler/Compiler.java
  
  Index: Compiler.java
  ===================================================================
  RCS file: /home/cvs/jakarta-tomcat-jasper/jasper2/src/share/org/apache/jasper/compiler/Compiler.java,v
  retrieving revision 1.91
  retrieving revision 1.92
  diff -u -r1.91 -r1.92
  --- Compiler.java	13 Jul 2004 22:47:23 -0000	1.91
  +++ Compiler.java	16 Aug 2004 23:48:35 -0000	1.92
  @@ -20,26 +20,17 @@
   import java.io.FileNotFoundException;
   import java.io.FileOutputStream;
   import java.io.OutputStreamWriter;
  -import java.io.PrintStream;
   import java.io.PrintWriter;
   import java.io.UnsupportedEncodingException;
   import java.net.URL;
   import java.net.URLConnection;
   import java.util.Iterator;
   import java.util.List;
  -import java.util.StringTokenizer;
   
   import org.apache.jasper.JasperException;
   import org.apache.jasper.JspCompilationContext;
   import org.apache.jasper.Options;
   import org.apache.jasper.servlet.JspServletWrapper;
  -import org.apache.jasper.util.SystemLogHandler;
  -import org.apache.tools.ant.BuildException;
  -import org.apache.tools.ant.DefaultLogger;
  -import org.apache.tools.ant.Project;
  -import org.apache.tools.ant.taskdefs.Javac;
  -import org.apache.tools.ant.types.Path;
  -import org.apache.tools.ant.types.PatternSet;
   
   /**
    * Main JSP compiler class. This class uses Ant for compiling.
  @@ -51,8 +42,8 @@
    * @author Remy Maucherat
    * @author Mark Roth
    */
  -public class Compiler {
  -    private static org.apache.commons.logging.Log log=
  +public abstract class Compiler {
  +    protected static org.apache.commons.logging.Log log=
           org.apache.commons.logging.LogFactory.getLog( Compiler.class );
   
       // ----------------------------------------------------------------- Static
  @@ -67,77 +58,22 @@
   
       protected JspCompilationContext ctxt;
   
  -    private ErrorDispatcher errDispatcher;
  -    private PageInfo pageInfo;
  -    private JspServletWrapper jsw;
  -    private JasperAntLogger logger;
  -    private TagFileProcessor tfp;
  -
  -    protected Project project=null;
  +    protected ErrorDispatcher errDispatcher;
  +    protected PageInfo pageInfo;
  +    protected JspServletWrapper jsw;
  +    protected TagFileProcessor tfp;
   
       protected Options options;
   
       protected Node.Nodes pageNodes;
       // ------------------------------------------------------------ Constructor
   
  -
  -    public Compiler(JspCompilationContext ctxt) {
  -        this(ctxt, null);
  -    }
  -
  -
  -    public Compiler(JspCompilationContext ctxt, JspServletWrapper jsw) {
  +    public void init(JspCompilationContext ctxt, JspServletWrapper jsw) {
           this.jsw = jsw;
           this.ctxt = ctxt;
           this.options = ctxt.getOptions();
       }
   
  -    // Lazy eval - if we don't need to compile we probably don't need the project
  -    private Project getProject() {
  -
  -        if( project!=null ) return project;
  -
  -        // Initializing project
  -        project = new Project();
  -        logger = new JasperAntLogger();
  -        logger.setOutputPrintStream(System.out);
  -        logger.setErrorPrintStream(System.err);
  -	logger.setMessageOutputLevel(Project.MSG_INFO);
  -        project.addBuildListener( logger);
  -	if (System.getProperty("catalina.home") != null) {
  -            project.setBasedir( System.getProperty("catalina.home"));
  -        }
  -        
  -        if( options.getCompiler() != null ) {
  -            if( log.isDebugEnabled() )
  -                log.debug("Compiler " + options.getCompiler() );
  -            project.setProperty("build.compiler", options.getCompiler() );
  -        }
  -        project.init();
  -        return project;
  -    }
  -
  -    class JasperAntLogger extends DefaultLogger {
  -
  -        private StringBuffer reportBuf = new StringBuffer();
  -
  -        protected void printMessage(final String message,
  -                                    final PrintStream stream,
  -                                    final int priority) {
  -        }
  -
  -        protected void log(String message) {
  -            reportBuf.append(message);
  -            reportBuf.append(System.getProperty("line.separator"));
  -        }
  -
  -        protected String getReport() {
  -            String report = reportBuf.toString();
  -            reportBuf.setLength(0);
  -            return report;
  -        }
  -    }
  -
       // --------------------------------------------------------- Public Methods
   
   
  @@ -146,7 +82,7 @@
        * @return a smap for the current JSP page, if one is generated,
        *         null otherwise
        */
  -    private String[] generateJava() throws Exception {
  +    protected String[] generateJava() throws Exception {
           
           String[] smapStr = null;
   
  @@ -298,139 +234,10 @@
       /** 
        * Compile the servlet from .java file to .class file
        */
  -    private void generateClass(String[] smap)
  -        throws FileNotFoundException, JasperException, Exception {
  -
  -        long t1=System.currentTimeMillis();
  -        String javaEncoding = ctxt.getOptions().getJavaEncoding();
  -        String javaFileName = ctxt.getServletJavaFileName();
  -        String classpath = ctxt.getClassPath(); 
  -
  -        String sep = System.getProperty("path.separator");
  -
  -        StringBuffer errorReport = new StringBuffer();
  -
  -        StringBuffer info=new StringBuffer();
  -        info.append("Compile: javaFileName=" + javaFileName + "\n" );
  -        info.append("    classpath=" + classpath + "\n" );
  -
  -        // Start capturing the System.err output for this thread
  -        SystemLogHandler.setThread();
  -
  -        // Initializing javac task
  -        getProject();
  -        Javac javac = (Javac) project.createTask("javac");
  -
  -        // Initializing classpath
  -        Path path = new Path(project);
  -        path.setPath(System.getProperty("java.class.path"));
  -        info.append("    cp=" + System.getProperty("java.class.path") + "\n");
  -        StringTokenizer tokenizer = new StringTokenizer(classpath, sep);
  -        while (tokenizer.hasMoreElements()) {
  -            String pathElement = tokenizer.nextToken();
  -            File repository = new File(pathElement);
  -            path.setLocation(repository);
  -            info.append("    cp=" + repository + "\n");
  -        }
  -
  -        if( log.isDebugEnabled() )
  -            log.debug( "Using classpath: " + System.getProperty("java.class.path") + sep
  -                       + classpath);
  -        
  -        // Initializing sourcepath
  -        Path srcPath = new Path(project);
  -        srcPath.setLocation(options.getScratchDir());
  -
  -        info.append("    work dir=" + options.getScratchDir() + "\n");
  -
  -        // Initialize and set java extensions
  -        String exts = System.getProperty("java.ext.dirs");
  -        if (exts != null) {
  -            Path extdirs = new Path(project);
  -            extdirs.setPath(exts);
  -            javac.setExtdirs(extdirs);
  -            info.append("    extension dir=" + exts + "\n");
  -        }
  -
  -        // Configure the compiler object
  -        javac.setEncoding(javaEncoding);
  -        javac.setClasspath(path);
  -        javac.setDebug(ctxt.getOptions().getClassDebugInfo());
  -        javac.setSrcdir(srcPath);
  -        javac.setOptimize(! ctxt.getOptions().getClassDebugInfo() );
  -        javac.setFork(ctxt.getOptions().getFork());
  -        info.append("    srcDir=" + srcPath + "\n" );
  -
  -        // Set the Java compiler to use
  -        if (options.getCompiler() != null) {
  -            javac.setCompiler(options.getCompiler());
  -            info.append("    compiler=" + options.getCompiler() + "\n");
  -        }
  -
  -        // Build includes path
  -        PatternSet.NameEntry includes = javac.createInclude();
  -
  -        includes.setName(ctxt.getJavaPath());
  -        info.append("    include="+ ctxt.getJavaPath() + "\n" );
  -
  -        BuildException be = null;
  -
  -        try {
  -            if (ctxt.getOptions().getFork()) {
  -                javac.execute();
  -            } else {
  -                synchronized(javacLock) {
  -                    javac.execute();
  -                }
  -            }
  -        } catch (BuildException e) {
  -            be = e;
  -            log.error( "Javac exception ", e);
  -            log.error( "Env: " + info.toString());
  -        }
  -
  -        errorReport.append(logger.getReport());
  -
  -        // Stop capturing the System.err output for this thread
  -        String errorCapture = SystemLogHandler.unsetThread();
  -        if (errorCapture != null) {
  -            errorReport.append(System.getProperty("line.separator"));
  -            errorReport.append(errorCapture);
  -        }
  -
  -        if (!ctxt.keepGenerated()) {
  -            File javaFile = new File(javaFileName);
  -            javaFile.delete();
  -        }
  -
  -        if (be != null) {
  -            String errorReportString = errorReport.toString();
  -            log.error("Error compiling file: " + javaFileName + " "
  -                      + errorReportString);
  -            JavacErrorDetail[] javacErrors = ErrorDispatcher.parseJavacErrors(
  -                        errorReportString, javaFileName, pageNodes);
  -            if (javacErrors != null) {
  -                errDispatcher.javacError(javacErrors);
  -            } else {
  -                errDispatcher.javacError(errorReportString, be);
  -            }
  -        }
  -
  -        long t2=System.currentTimeMillis();
  -        if( t2-t1 > 500 ) {
  -            log.debug( "Compiled " + javaFileName + " " + (t2-t1));
  -        }
  -
  -	if (ctxt.isPrototypeMode()) {
  -	    return;
  -	}
  -
  -        // JSR45 Support
  -        if (! options.isSmapSuppressed()) {
  -            SmapUtil.installSmap(smap);
  -        }
  -    }
  -
  +    protected abstract void generateClass(String[] smap)
  +        throws FileNotFoundException, JasperException, Exception;
  +    
  +    
       /** 
        * Compile the jsp file from the current engine context
        */
  @@ -482,8 +289,6 @@
               // memory footprint.
               tfp = null;
               errDispatcher = null;
  -            logger = null;
  -            project = null;
               pageInfo = null;
               pageNodes = null;
               if (ctxt.getWriter() != null) {
  
  
  
  1.1                  jakarta-tomcat-jasper/jasper2/src/share/org/apache/jasper/compiler/AntCompiler.java
  
  Index: AntCompiler.java
  ===================================================================
  /*
   * Copyright 1999,2004 The Apache Software Foundation.
   * 
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   * 
   *      http://www.apache.org/licenses/LICENSE-2.0
   * 
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  
  package org.apache.jasper.compiler;
  
  import java.io.File;
  import java.io.FileNotFoundException;
  import java.io.PrintStream;
  import java.util.StringTokenizer;
  
  import org.apache.jasper.JasperException;
  import org.apache.jasper.util.SystemLogHandler;
  import org.apache.tools.ant.BuildException;
  import org.apache.tools.ant.DefaultLogger;
  import org.apache.tools.ant.Project;
  import org.apache.tools.ant.taskdefs.Javac;
  import org.apache.tools.ant.types.Path;
  import org.apache.tools.ant.types.PatternSet;
  
  /**
   * Main JSP compiler class. This class uses Ant for compiling.
   *
   * @author Anil K. Vijendran
   * @author Mandar Raje
   * @author Pierre Delisle
   * @author Kin-man Chung
   * @author Remy Maucherat
   * @author Mark Roth
   */
  public class AntCompiler extends Compiler {
  
      
      // ----------------------------------------------------- Instance Variables
  
      protected Project project=null;
      protected JasperAntLogger logger;
  
      // ------------------------------------------------------------ Constructor
  
      // Lazy eval - if we don't need to compile we probably don't need the project
      protected Project getProject() {
          
          if( project!=null ) return project;
          
          // Initializing project
          project = new Project();
          logger = new JasperAntLogger();
          logger.setOutputPrintStream(System.out);
          logger.setErrorPrintStream(System.err);
          logger.setMessageOutputLevel(Project.MSG_INFO);
          project.addBuildListener( logger);
          if (System.getProperty("catalina.home") != null) {
              project.setBasedir( System.getProperty("catalina.home"));
          }
          
          if( options.getCompiler() != null ) {
              if( log.isDebugEnabled() )
                  log.debug("Compiler " + options.getCompiler() );
              project.setProperty("build.compiler", options.getCompiler() );
          }
          project.init();
          return project;
      }
      
      class JasperAntLogger extends DefaultLogger {
          
          protected StringBuffer reportBuf = new StringBuffer();
          
          protected void printMessage(final String message,
                  final PrintStream stream,
                  final int priority) {
          }
          
          protected void log(String message) {
              reportBuf.append(message);
              reportBuf.append(System.getProperty("line.separator"));
          }
          
          protected String getReport() {
              String report = reportBuf.toString();
              reportBuf.setLength(0);
              return report;
          }
      }
      
      // --------------------------------------------------------- Public Methods
  
  
      /** 
       * Compile the servlet from .java file to .class file
       */
      protected void generateClass(String[] smap)
          throws FileNotFoundException, JasperException, Exception {
          
          long t1=System.currentTimeMillis();
          String javaEncoding = ctxt.getOptions().getJavaEncoding();
          String javaFileName = ctxt.getServletJavaFileName();
          String classpath = ctxt.getClassPath(); 
          
          String sep = System.getProperty("path.separator");
          
          StringBuffer errorReport = new StringBuffer();
          
          StringBuffer info=new StringBuffer();
          info.append("Compile: javaFileName=" + javaFileName + "\n" );
          info.append("    classpath=" + classpath + "\n" );
          
          // Start capturing the System.err output for this thread
          SystemLogHandler.setThread();
          
          // Initializing javac task
          getProject();
          Javac javac = (Javac) project.createTask("javac");
          
          // Initializing classpath
          Path path = new Path(project);
          path.setPath(System.getProperty("java.class.path"));
          info.append("    cp=" + System.getProperty("java.class.path") + "\n");
          StringTokenizer tokenizer = new StringTokenizer(classpath, sep);
          while (tokenizer.hasMoreElements()) {
              String pathElement = tokenizer.nextToken();
              File repository = new File(pathElement);
              path.setLocation(repository);
              info.append("    cp=" + repository + "\n");
          }
          
          if( log.isDebugEnabled() )
              log.debug( "Using classpath: " + System.getProperty("java.class.path") + sep
                      + classpath);
          
          // Initializing sourcepath
          Path srcPath = new Path(project);
          srcPath.setLocation(options.getScratchDir());
          
          info.append("    work dir=" + options.getScratchDir() + "\n");
          
          // Initialize and set java extensions
          String exts = System.getProperty("java.ext.dirs");
          if (exts != null) {
              Path extdirs = new Path(project);
              extdirs.setPath(exts);
              javac.setExtdirs(extdirs);
              info.append("    extension dir=" + exts + "\n");
          }
          
          // Configure the compiler object
          javac.setEncoding(javaEncoding);
          javac.setClasspath(path);
          javac.setDebug(ctxt.getOptions().getClassDebugInfo());
          javac.setSrcdir(srcPath);
          javac.setOptimize(! ctxt.getOptions().getClassDebugInfo() );
          javac.setFork(ctxt.getOptions().getFork());
          info.append("    srcDir=" + srcPath + "\n" );
          
          // Set the Java compiler to use
          if (options.getCompiler() != null) {
              javac.setCompiler(options.getCompiler());
              info.append("    compiler=" + options.getCompiler() + "\n");
          }
          
          // Build includes path
          PatternSet.NameEntry includes = javac.createInclude();
          
          includes.setName(ctxt.getJavaPath());
          info.append("    include="+ ctxt.getJavaPath() + "\n" );
          
          BuildException be = null;
          
          try {
              if (ctxt.getOptions().getFork()) {
                  javac.execute();
              } else {
                  synchronized(javacLock) {
                      javac.execute();
                  }
              }
          } catch (BuildException e) {
              be = e;
              log.error( "Javac exception ", e);
              log.error( "Env: " + info.toString());
          }
          
          errorReport.append(logger.getReport());
          
          // Stop capturing the System.err output for this thread
          String errorCapture = SystemLogHandler.unsetThread();
          if (errorCapture != null) {
              errorReport.append(System.getProperty("line.separator"));
              errorReport.append(errorCapture);
          }
          
          if (!ctxt.keepGenerated()) {
              File javaFile = new File(javaFileName);
              javaFile.delete();
          }
          
          if (be != null) {
              String errorReportString = errorReport.toString();
              log.error("Error compiling file: " + javaFileName + " "
                      + errorReportString);
              JavacErrorDetail[] javacErrors = ErrorDispatcher.parseJavacErrors(
                      errorReportString, javaFileName, pageNodes);
              if (javacErrors != null) {
                  errDispatcher.javacError(javacErrors);
              } else {
                  errDispatcher.javacError(errorReportString, be);
              }
          }
          
          long t2=System.currentTimeMillis();
          if( log.isDebugEnabled() ) {
              log.debug( "Compiled " + ctxt.getServletJavaFileName() + " " + (t2-t1) + "ms");
          }
          
          logger = null;
          project = null;
          
          if (ctxt.isPrototypeMode()) {
              return;
          }
          
          // JSR45 Support
          if (! options.isSmapSuppressed()) {
              SmapUtil.installSmap(smap);
          }
      }
  
      
  }
  
  
  
  1.1                  jakarta-tomcat-jasper/jasper2/src/share/org/apache/jasper/compiler/JDTCompiler.java
  
  Index: JDTCompiler.java
  ===================================================================
  /*
   * Copyright 1999,2004 The Apache Software Foundation.
   * 
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   * 
   *      http://www.apache.org/licenses/LICENSE-2.0
   * 
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  
  package org.apache.jasper.compiler;
  
  import java.io.BufferedOutputStream;
  import java.io.BufferedReader;
  import java.io.ByteArrayOutputStream;
  import java.io.File;
  import java.io.FileNotFoundException;
  import java.io.FileOutputStream;
  import java.io.FileReader;
  import java.io.IOException;
  import java.io.InputStream;
  import java.io.Reader;
  import java.util.ArrayList;
  import java.util.HashMap;
  import java.util.Locale;
  import java.util.Map;
  import java.util.StringTokenizer;
  
  import org.apache.jasper.JasperException;
  import org.eclipse.jdt.core.compiler.IProblem;
  import org.eclipse.jdt.internal.compiler.ClassFile;
  import org.eclipse.jdt.internal.compiler.CompilationResult;
  import org.eclipse.jdt.internal.compiler.Compiler;
  import org.eclipse.jdt.internal.compiler.DefaultErrorHandlingPolicies;
  import org.eclipse.jdt.internal.compiler.ICompilerRequestor;
  import org.eclipse.jdt.internal.compiler.IErrorHandlingPolicy;
  import org.eclipse.jdt.internal.compiler.IProblemFactory;
  import org.eclipse.jdt.internal.compiler.classfmt.ClassFileReader;
  import org.eclipse.jdt.internal.compiler.env.ICompilationUnit;
  import org.eclipse.jdt.internal.compiler.env.INameEnvironment;
  import org.eclipse.jdt.internal.compiler.env.NameEnvironmentAnswer;
  import org.eclipse.jdt.internal.compiler.impl.CompilerOptions;
  import org.eclipse.jdt.internal.compiler.problem.DefaultProblemFactory;
  
  /**
   * JDT class compiler. This compiler will load source dependencies from the
   * context classloader, reducing dramatically disk access during 
   * the compilation process.
   *
   * @author Cocoon2
   * @author Remy Maucherat
   */
  public class JDTCompiler extends org.apache.jasper.compiler.Compiler {
  
      
      static boolean target14;
      static boolean source14;
  
      static {
          // Detect JDK version we are running under
          String version = System.getProperty("java.specification.version");
          try {
              source14 = target14 = Float.parseFloat(version) >= 1.4;
          } catch (NumberFormatException e) {
              source14 = target14 = false;
          }
      }
  
  
      /** 
       * Compile the servlet from .java file to .class file
       */
      protected void generateClass(String[] smap)
          throws FileNotFoundException, JasperException, Exception {
  
          long t1=System.currentTimeMillis();
          
          final String sourceFile = ctxt.getServletJavaFileName();
          final String outputDir = ctxt.getOptions().getScratchDir().getAbsolutePath();
          String packageName = ctxt.getServletPackageName();
          final String targetClassName = 
              ((packageName.length() != 0) ? (packageName + ".") : "") 
                      + ctxt.getServletClassName();
          final ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
          String[] fileNames = new String[] {sourceFile};
          String[] classNames = new String[] {targetClassName};
          final ArrayList problemList = new ArrayList();
          
          class CompilationUnit implements ICompilationUnit {
  
              String className;
              String sourceFile;
  
              CompilationUnit(String sourceFile, String className) {
                  this.className = className;
                  this.sourceFile = sourceFile;
              }
  
              public char[] getFileName() {
                  return className.toCharArray();
              }
              
              public char[] getContents() {
                  char[] result = null;
                  try {
                      Reader reader = new BufferedReader(new FileReader(sourceFile));
                      if (reader != null) {
                          char[] chars = new char[8192];
                          StringBuffer buf = new StringBuffer();
                          int count;
                          while ((count = reader.read(chars, 0, 
                                                      chars.length)) > 0) {
                              buf.append(chars, 0, count);
                          }
                          result = new char[buf.length()];
                          buf.getChars(0, result.length, result, 0);
                      }
                  } catch (IOException e) {
                      log.error("Compilation error", e);
                  }
                  return result;
              }
              
              public char[] getMainTypeName() {
                  int dot = className.lastIndexOf('.');
                  if (dot > 0) {
                      return className.substring(dot + 1).toCharArray();
                  }
                  return className.toCharArray();
              }
              
              public char[][] getPackageName() {
                  StringTokenizer izer = 
                      new StringTokenizer(className, ".");
                  char[][] result = new char[izer.countTokens()-1][];
                  for (int i = 0; i < result.length; i++) {
                      String tok = izer.nextToken();
                      result[i] = tok.toCharArray();
                  }
                  return result;
              }
          }
  
          final INameEnvironment env = new INameEnvironment() {
  
                  public NameEnvironmentAnswer 
                      findType(char[][] compoundTypeName) {
                      String result = "";
                      String sep = "";
                      for (int i = 0; i < compoundTypeName.length; i++) {
                          result += sep;
                          result += new String(compoundTypeName[i]);
                          sep = ".";
                      }
                      return findType(result);
                  }
  
                  public NameEnvironmentAnswer 
                      findType(char[] typeName, 
                               char[][] packageName) {
                          String result = "";
                          String sep = "";
                          for (int i = 0; i < packageName.length; i++) {
                              result += sep;
                              result += new String(packageName[i]);
                              sep = ".";
                          }
                          result += sep;
                          result += new String(typeName);
                          return findType(result);
                  }
                  
                  private NameEnvironmentAnswer findType(String className) {
  
                      try {
                          if (className.equals(targetClassName)) {
                              ICompilationUnit compilationUnit = 
                                  new CompilationUnit(sourceFile, className);
                              return 
                                  new NameEnvironmentAnswer(compilationUnit);
                          }
                          String resourceName = 
                              className.replace('.', '/') + ".class";
                          InputStream is = 
                              classLoader.getResourceAsStream(resourceName);
                          if (is != null) {
                              byte[] classBytes;
                              byte[] buf = new byte[8192];
                              ByteArrayOutputStream baos = 
                                  new ByteArrayOutputStream(buf.length);
                              int count;
                              while ((count = is.read(buf, 0, buf.length)) > 0) {
                                  baos.write(buf, 0, count);
                              }
                              baos.flush();
                              classBytes = baos.toByteArray();
                              char[] fileName = className.toCharArray();
                              ClassFileReader classFileReader = 
                                  new ClassFileReader(classBytes, fileName, 
                                                      true);
                              return 
                                  new NameEnvironmentAnswer(classFileReader);
                          }
                      } catch (IOException exc) {
                          log.error("Compilation error", exc);
                      } catch (org.eclipse.jdt.internal.compiler.classfmt.ClassFormatException exc) {
                          log.error("Compilation error", exc);
                      }
                      return null;
                  }
  
                  private boolean isPackage(String result) {
                      if (result.equals(targetClassName)) {
                          return false;
                      }
                      String resourceName = result.replace('.', '/') + ".class";
                      InputStream is = 
                          classLoader.getResourceAsStream(resourceName);
                      return is == null;
                  }
  
                  public boolean isPackage(char[][] parentPackageName, 
                                           char[] packageName) {
                      String result = "";
                      String sep = "";
                      if (parentPackageName != null) {
                          for (int i = 0; i < parentPackageName.length; i++) {
                              result += sep;
                              String str = new String(parentPackageName[i]);
                              result += str;
                              sep = ".";
                          }
                      }
                      String str = new String(packageName);
                      if (Character.isUpperCase(str.charAt(0))) {
                          if (!isPackage(result)) {
                              return false;
                          }
                      }
                      result += sep;
                      result += str;
                      return isPackage(result);
                  }
  
                  public void cleanup() {
                  }
  
              };
  
          final IErrorHandlingPolicy policy = 
              DefaultErrorHandlingPolicies.proceedWithAllProblems();
  
          final Map settings = new HashMap();
          settings.put(CompilerOptions.OPTION_LineNumberAttribute,
                       CompilerOptions.GENERATE);
          settings.put(CompilerOptions.OPTION_SourceFileAttribute,
                       CompilerOptions.GENERATE);
          settings.put(CompilerOptions.OPTION_ReportDeprecation,
                       CompilerOptions.IGNORE);
          if (ctxt.getOptions().getJavaEncoding() != null) {
              settings.put(CompilerOptions.OPTION_Encoding,
                      ctxt.getOptions().getJavaEncoding());
          }
          if (ctxt.getOptions().getClassDebugInfo()) {
              settings.put(CompilerOptions.OPTION_LocalVariableAttribute,
                           CompilerOptions.GENERATE);
          }
          if (source14) {
              settings.put(CompilerOptions.OPTION_Source,
                           CompilerOptions.VERSION_1_4);
          }
          if (target14) {
              settings.put(CompilerOptions.OPTION_TargetPlatform,
                           CompilerOptions.VERSION_1_4);
          }
          final IProblemFactory problemFactory = 
              new DefaultProblemFactory(Locale.getDefault());
          
          final ICompilerRequestor requestor = new ICompilerRequestor() {
                  public void acceptResult(CompilationResult result) {
                      try {
                          if (result.hasProblems()) {
                              IProblem[] problems = result.getProblems();
                              for (int i = 0; i < problems.length; i++) {
                                  IProblem problem = problems[i];
                                  String name = 
                                      new String(problems[i].getOriginatingFileName());
                                  try {
                                      problemList.add(ErrorDispatcher.createJavacError
                                          (name, pageNodes, new StringBuffer(problem.getMessage()), 
                                                  problem.getSourceLineNumber()));
                                  } catch (JasperException e) {
                                      log.error("Error visiting node", e);
                                  }
                              }
                          } else {
                              ClassFile[] classFiles = result.getClassFiles();
                              for (int i = 0; i < classFiles.length; i++) {
                                  ClassFile classFile = classFiles[i];
                                  char[][] compoundName = 
                                      classFile.getCompoundName();
                                  String className = "";
                                  String sep = "";
                                  for (int j = 0; 
                                       j < compoundName.length; j++) {
                                      className += sep;
                                      className += new String(compoundName[j]);
                                      sep = ".";
                                  }
                                  byte[] bytes = classFile.getBytes();
                                  String outFile = outputDir + "/" + 
                                      className.replace('.', '/') + ".class";
                                  FileOutputStream fout = 
                                      new FileOutputStream(outFile);
                                  BufferedOutputStream bos = 
                                      new BufferedOutputStream(fout);
                                  bos.write(bytes);
                                  bos.close();
                              }
                          }
                      } catch (IOException exc) {
                          log.error("Compilation error", exc);
                      }
                  }
              };
  
          ICompilationUnit[] compilationUnits = 
              new ICompilationUnit[classNames.length];
          for (int i = 0; i < compilationUnits.length; i++) {
              String className = classNames[i];
              compilationUnits[i] = new CompilationUnit(fileNames[i], className);
          }
          Compiler compiler = new Compiler(env,
                                           policy,
                                           settings,
                                           requestor,
                                           problemFactory);
          compiler.compile(compilationUnits);
  
          if (!ctxt.keepGenerated()) {
              File javaFile = new File(ctxt.getServletJavaFileName());
              javaFile.delete();
          }
      
          if (!problemList.isEmpty()) {
              JavacErrorDetail[] jeds = 
                  (JavacErrorDetail[]) problemList.toArray(new JavacErrorDetail[0]);
              errDispatcher.javacError(jeds);
          }
          
          long t2=System.currentTimeMillis();
          if( log.isDebugEnabled() ) {
              log.debug( "Compiled " + ctxt.getServletJavaFileName() + " " + (t2-t1) + "ms");
          }
  
          if (ctxt.isPrototypeMode()) {
              return;
          }
  
          // JSR45 Support
          if (! options.isSmapSuppressed()) {
              SmapUtil.installSmap(smap);
          }
          
      }
      
      
  }
  
  
  
  1.49      +16 -1     jakarta-tomcat-jasper/jasper2/src/share/org/apache/jasper/JspCompilationContext.java
  
  Index: JspCompilationContext.java
  ===================================================================
  RCS file: /home/cvs/jakarta-tomcat-jasper/jasper2/src/share/org/apache/jasper/JspCompilationContext.java,v
  retrieving revision 1.48
  retrieving revision 1.49
  diff -u -r1.48 -r1.49
  --- JspCompilationContext.java	24 May 2004 21:17:27 -0000	1.48
  +++ JspCompilationContext.java	16 Aug 2004 23:48:36 -0000	1.49
  @@ -194,7 +194,22 @@
           if (jspCompiler != null ) {
               return jspCompiler;
           }
  -        jspCompiler = new Compiler(this, jsw);
  +        jspCompiler = null;
  +        try {
  +            jspCompiler = 
  +                (Compiler) Class.forName("org.apache.jasper.compiler.JDTCompiler").newInstance();
  +        } catch (Throwable t) {
  +            // Log ?
  +            // FIXME: log
  +        }
  +        try {
  +            jspCompiler = 
  +                (Compiler) Class.forName("org.apache.jasper.compiler.AntCompiler").newInstance();
  +        } catch (Throwable t) {
  +            // Log ?
  +            // FIXME: log
  +        }
  +        jspCompiler.init(this, jsw);
           return jspCompiler;
       }
   
  
  
  

---------------------------------------------------------------------
To unsubscribe, e-mail: tomcat-dev-unsubscribe@jakarta.apache.org
For additional commands, e-mail: tomcat-dev-help@jakarta.apache.org


Re: cvs commit: jakarta-tomcat-jasper/jasper2/src/share/org/apache/jasper JspCompilationContext.java

Posted by Bill Barker <wb...@wilshire.com>.
>   -        jspCompiler = new Compiler(this, jsw);
>   +        jspCompiler = null;
>   +        try {
>   +            jspCompiler =
>   +                (Compiler)
Class.forName("org.apache.jasper.compiler.JDTCompiler").newInstance();
>   +        } catch (Throwable t) {
>   +            // Log ?
>   +            // FIXME: log
>   +        }
>   +        try {
>   +            jspCompiler =
>   +                (Compiler)
Class.forName("org.apache.jasper.compiler.AntCompiler").newInstance();
>   +        } catch (Throwable t) {
>   +            // Log ?
>   +            // FIXME: log
>   +        }
>   +        jspCompiler.init(this, jsw);
>            return jspCompiler;
>        }
>

This will always give you an AntCompiler.