vgritsenko    2003/07/29 11:49:30

  Modified:    .        changes.xml build.xml
               lib      jars.xml
               src/java/org/apache/cocoon/components/language/programming/java
                        JavaLanguage.java Jikes.java NullFormatter.java
                        javac.xconf pizza.xconf
  Added:       src/java/org/apache/cocoon/components/language/programming/java
                        EclipseJavaCompiler.java
  Log:
  backport eclipse compiler from 2.1
  
  Revision  Changes    Path
  1.32      +4 -1      cocoon-2.0/changes.xml
  
  Index: changes.xml
  ===================================================================
  RCS file: /home/cvs/cocoon-2.0/changes.xml,v
  retrieving revision 1.31
  retrieving revision 1.32
  diff -u -r1.31 -r1.32
  --- changes.xml       29 Jul 2003 17:41:29 -0000      1.31
  +++ changes.xml       29 Jul 2003 18:49:28 -0000      1.32
  @@ -43,6 +43,9 @@
    </devs>
   
    <release version="@version@" date="@date@">
  +  <action dev="VG" type="add">
  +    Backported Eclipse JDT compiler from the 2.1.
  +  </action>
     <action dev="VG" type="update">
       Updated Jisp to the latest released version, 2.5.1.
     </action>
  
  
  
  1.4       +21 -2     cocoon-2.0/build.xml
  
  Index: build.xml
  ===================================================================
  RCS file: /home/cvs/cocoon-2.0/build.xml,v
  retrieving revision 1.3
  retrieving revision 1.4
  diff -u -r1.3 -r1.4
  --- build.xml 3 Jul 2003 00:54:43 -0000       1.3
  +++ build.xml 29 Jul 2003 18:49:28 -0000      1.4
  @@ -322,6 +322,10 @@
                        property="pizza.present" 
                        classname="net.sf.pizzacompiler.compiler.Main"/>
   
  +    <class-available classpathref="classpath"
  +                     property="eclipse.present" 
  +                     classname="org.eclipse.jdt.internal.compiler.Compiler"/>
  +
       <class-available classpathref="classpath" 
                        property="xmldb.present" 
                        classname="org.xmldb.api.DatabaseManager"/>
  @@ -676,6 +680,17 @@
       </antcall>
     </target>
   
  +  <!-- Outputs a warning if org.eclipse.jdt.internal.compiler.* classes are 
missing during compilation -->
  +  <target name="eclipse-warn" unless="eclipse.present" 
depends="optional-tests">
  +    <antcall target="op-warning">
  +      <param name="thing" value="Eclipse"/>
  +      <param name="recovery"
  +        value="Get the Eclipse JDT package from http://www.eclipse.org/jdt 
and place the jar in the lib/optional dir"/>
  +      <param name="message"
  +             value="Eclipse JDT is the Java compiler which works using 
classloader."/>
  +    </antcall>
  +  </target>
  +
     <!-- Outputs a warning if org.apache.poi.* classes are missing during 
compilation -->
     <target name="poi-warn" unless="poi.present" depends="optional-tests">
       <antcall target="op-warning">
  @@ -703,7 +718,7 @@
     <!-- Print out warnings for optional components                          
-->
     <!-- =================================================================== 
-->
     <target name="optional-warnings" 
  -          depends="bsf-warn, rhino-warn, jfor-warn, xmldb-warn, xt-warn, 
php-warn, naming-warn, svg-warn, fop-warn, tidy-warn, maybeupload-warn, 
lucene-warn, deli-warn, velocity-warn, hsqldb-warn, resolver-warn, jisp-warn, 
pizza-warn, poi-warn, commons-logging-warn">
  +          depends="bsf-warn, rhino-warn, jfor-warn, xmldb-warn, xt-warn, 
php-warn, naming-warn, svg-warn, fop-warn, tidy-warn, maybeupload-warn, 
lucene-warn, deli-warn, velocity-warn, hsqldb-warn, resolver-warn, jisp-warn, 
pizza-warn, eclipse-warn, poi-warn, commons-logging-warn">
     </target>
   
   
  @@ -731,8 +746,12 @@
                 
           <exclude name="**/java/Pizza.java"         unless="pizza.present"/>
           <exclude name="**/java/pizza.x*"           unless="pizza.present"/>
  +        <exclude name="**/java/Eclipse*.java"      unless="eclipse.present"/>
  +        <exclude name="**/java/eclipse.x*"         unless="eclipse.present"/>
   -->
           <exclude name="**/java/javac.x*"           if="pizza.present"/>
  +        <exclude name="**/java/javac.x*"           if="eclipse.present"/>
  +        <exclude name="**/java/pizza.x*"           if="eclipse.present"/>
   <!--
           <exclude name="**/JSP*.java"               unless="servlet.present"/>
           <exclude name="**/Jsp*.java"               unless="servlet.present"/>
  
  
  
  1.10      +12 -5     cocoon-2.0/lib/jars.xml
  
  Index: jars.xml
  ===================================================================
  RCS file: /home/cvs/cocoon-2.0/lib/jars.xml,v
  retrieving revision 1.9
  retrieving revision 1.10
  diff -u -r1.9 -r1.10
  --- jars.xml  29 Jul 2003 17:41:30 -0000      1.9
  +++ jars.xml  29 Jul 2003 18:49:29 -0000      1.10
  @@ -192,7 +192,7 @@
       <lib>core/commons-collections-2.1.jar</lib>
       <homepage>http://jakarta.apache.org/commons/collections.html</homepage>
     </file>
  -<file>
  +  <file>
       <title>Jakarta Commons Lang</title>
       <description>The Lang Component provides a host of helper utilities for
         the java.lang API.</description>
  @@ -201,7 +201,7 @@
       <homepage>http://jakarta.apache.org/commons/lang.html</homepage>
     </file>
     <file>
  -    <title>Jakart Commons httpClient</title>
  +    <title>Jakarta Commons httpClient</title>
       <description>Although the java.net package provides basic support for 
accessing
         resources via HTTP, it doesn't provide the full flexibility or
         functionality needed by many applications. The Jakarta Commons HTTP 
Client
  @@ -221,9 +221,9 @@
       <homepage>http://jakarta.apache.org/regexp/</homepage>
     </file>
     <file>
  -    <title>Jakarta logkit</title>
  +    <title>Jakarta Logkit</title>
       <description>jakarta-avalon-logkit is a logging toolkit designed for 
secure
  -      performance orientated logging in applications.</description>
  +      performance oriented logging in applications.</description>
       <used-by>Cocoon logging</used-by>
       <lib>core/logkit-20020529.jar</lib>
       <homepage>http://jakarta.apache.org/avalon/logkit/</homepage>
  @@ -373,11 +373,18 @@
       <homepage>http://www.weft.co.uk/library/maybeupload/</homepage>
     </file>
     <file>
  -    <title>Java compiler</title>
  +    <title>Pizza Java Compiler</title>
       <description>Java Compiler</description>
       <used-by>XSP</used-by>
       <lib>optional/pizza-1.1.jar</lib>
       <homepage>http://pizzacompiler.sourceforge.net/</homepage>
  +  </file>
  +  <file>
  +    <title>Eclipse Java Development Tools Core</title>
  +    <description>Eclipse Java Compiler</description>
  +    <used-by>XSP</used-by>
  +    <lib>optional/jdtcore-2.1.0.jar</lib>
  +    <homepage>http://www.eclipse.org/jdt</homepage>
     </file>
     <file>
       <title>XML RDF parser</title>
  
  
  
  1.2       +18 -15    
cocoon-2.0/src/java/org/apache/cocoon/components/language/programming/java/JavaLanguage.java
  
  Index: JavaLanguage.java
  ===================================================================
  RCS file: 
/home/cvs/cocoon-2.0/src/java/org/apache/cocoon/components/language/programming/java/JavaLanguage.java,v
  retrieving revision 1.1
  retrieving revision 1.2
  diff -u -r1.1 -r1.2
  --- JavaLanguage.java 9 Mar 2003 00:02:06 -0000       1.1
  +++ JavaLanguage.java 29 Jul 2003 18:49:29 -0000      1.2
  @@ -54,6 +54,7 @@
   import org.apache.avalon.framework.activity.Initializable;
   import org.apache.avalon.framework.component.ComponentManager;
   import org.apache.avalon.framework.component.Composable;
  +import org.apache.avalon.framework.logger.Loggable;
   import org.apache.avalon.framework.parameters.ParameterException;
   import org.apache.avalon.framework.parameters.Parameters;
   import org.apache.avalon.framework.thread.ThreadSafe;
  @@ -63,6 +64,7 @@
   import org.apache.cocoon.components.language.markup.xsp.XSLTExtension;
   import 
org.apache.cocoon.components.language.programming.CompiledProgrammingLanguage;
   import org.apache.cocoon.components.language.programming.CompilerError;
  +import org.apache.cocoon.components.language.programming.LanguageCompiler;
   import org.apache.cocoon.util.ClassUtils;
   import org.apache.cocoon.util.JavaArchiveFilter;
   
  @@ -199,28 +201,29 @@
               throws LanguageException {
   
           try {
  -            AbstractJavaCompiler compiler = (AbstractJavaCompiler) 
this.compilerClass.newInstance();
  -            // AbstractJavaCompiler is Loggable
  -            compiler.setLogger(getLogger());
  +            LanguageCompiler compiler = (LanguageCompiler) 
this.compilerClass.newInstance();
  +            if (compiler instanceof Loggable) {
  +                // AbstractJavaCompiler is Loggable
  +                ((Loggable)compiler).setLogger(getLogger());
  +            }
   
               int pos = name.lastIndexOf(File.separatorChar);
               String filename = name.substring(pos + 1);
  -            String pathname =
  -                    baseDirectory.getCanonicalPath() + File.separator +
  -                    name.substring(0, pos).replace(File.separatorChar, '/');
  -            String filename_abs = pathname + File.separator + filename
  -                    + "." + this.getSourceExtension();
  -
  -            compiler.setFile(filename_abs);
  -            compiler.setSource(pathname);
  -            compiler.setDestination(baseDirectory.getCanonicalPath());
  -            compiler.setClasspath(baseDirectory.getCanonicalPath() + 
this.classpath);
  +
  +            final String basePath = baseDirectory.getCanonicalPath();
  +            String filepath = basePath + File.separator
  +                    + name + "." + getSourceExtension();
  +
  +            compiler.setFile(filepath);
  +            compiler.setSource(basePath);
  +            compiler.setDestination(basePath);
  +            compiler.setClasspath(basePath + this.classpath);
   
               if (encoding != null) {
                   compiler.setEncoding(encoding);
               }
   
  -            getLogger().debug("Compiling " + filename_abs);
  +            getLogger().debug("Compiling " + filepath);
               if (!compiler.compile()) {
                   StringBuffer message = new StringBuffer("Error compiling ");
                   message.append(filename);
  
  
  
  1.2       +1 -2      
cocoon-2.0/src/java/org/apache/cocoon/components/language/programming/java/Jikes.java
  
  Index: Jikes.java
  ===================================================================
  RCS file: 
/home/cvs/cocoon-2.0/src/java/org/apache/cocoon/components/language/programming/java/Jikes.java,v
  retrieving revision 1.1
  retrieving revision 1.2
  diff -u -r1.1 -r1.2
  --- Jikes.java        9 Mar 2003 00:02:07 -0000       1.1
  +++ Jikes.java        29 Jul 2003 18:49:29 -0000      1.2
  @@ -74,7 +74,6 @@
   
           private BufferedInputStream stream;
           private boolean endOfStream = false;
  -        private boolean stopSignal  = false;
           private int SLEEP_TIME = 5;
           private OutputStream out;
   
  
  
  
  1.2       +2 -2      
cocoon-2.0/src/java/org/apache/cocoon/components/language/programming/java/NullFormatter.java
  
  Index: NullFormatter.java
  ===================================================================
  RCS file: 
/home/cvs/cocoon-2.0/src/java/org/apache/cocoon/components/language/programming/java/NullFormatter.java,v
  retrieving revision 1.1
  retrieving revision 1.2
  diff -u -r1.1 -r1.2
  --- NullFormatter.java        9 Mar 2003 00:02:07 -0000       1.1
  +++ NullFormatter.java        29 Jul 2003 18:49:29 -0000      1.2
  @@ -72,7 +72,7 @@
        * @return The formatted source code
        */
       public String format(String code, String encoding) {
  -    getLogger().debug("NullFormatter called");
  +        getLogger().debug("NullFormatter called");
           return code;
       }
   }
  
  
  
  1.2       +2 -0      
cocoon-2.0/src/java/org/apache/cocoon/components/language/programming/java/javac.xconf
  
  Index: javac.xconf
  ===================================================================
  RCS file: 
/home/cvs/cocoon-2.0/src/java/org/apache/cocoon/components/language/programming/java/javac.xconf,v
  retrieving revision 1.1
  retrieving revision 1.2
  diff -u -r1.1 -r1.2
  --- javac.xconf       9 Mar 2003 00:02:07 -0000       1.1
  +++ javac.xconf       29 Jul 2003 18:49:29 -0000      1.2
  @@ -6,6 +6,8 @@
              Possible variants are:
                Javac. Requires javac.jar (included with JDK as lib/toools.jar).
                Pizza. Requires pizza.jar (included with Cocoon distribution).
  +             EclipseJavaCompiler. The Eclipse JTD java compiler
  +                    (included with Cocoon distribution).
                Jikes. Requires IBM jikes compiler to be present in the PATH  
-->
         <parameter name="compiler" 
value="org.apache.cocoon.components.language.programming.java.Javac"/>
   </xconf>
  
  
  
  1.2       +2 -0      
cocoon-2.0/src/java/org/apache/cocoon/components/language/programming/java/pizza.xconf
  
  Index: pizza.xconf
  ===================================================================
  RCS file: 
/home/cvs/cocoon-2.0/src/java/org/apache/cocoon/components/language/programming/java/pizza.xconf,v
  retrieving revision 1.1
  retrieving revision 1.2
  diff -u -r1.1 -r1.2
  --- pizza.xconf       9 Mar 2003 00:02:07 -0000       1.1
  +++ pizza.xconf       29 Jul 2003 18:49:29 -0000      1.2
  @@ -6,6 +6,8 @@
              Possible variants are:
                Javac. Requires javac.jar (included with JDK as lib/toools.jar).
                Pizza. Requires pizza.jar (included with Cocoon distribution).
  +             EclipseJavaCompiler. The Eclipse JTD java compiler
  +                    (included with Cocoon distribution).
                Jikes. Requires IBM jikes compiler to be present in the PATH  
-->
         <parameter name="compiler" 
value="org.apache.cocoon.components.language.programming.java.Pizza"/>
   </xconf>
  
  
  
  1.1                  
cocoon-2.0/src/java/org/apache/cocoon/components/language/programming/java/EclipseJavaCompiler.java
  
  Index: EclipseJavaCompiler.java
  ===================================================================
  /*
  
   ============================================================================
                     The Apache Software License, Version 1.1
   ============================================================================
  
   Copyright (C) 1999-2003 The Apache Software Foundation. All rights reserved.
  
   Redistribution and use in source and binary forms, with or without modifica-
   tion, are permitted provided that the following conditions are met:
  
   1. Redistributions of  source code must  retain the above copyright  notice,
      this list of conditions and the following disclaimer.
  
   2. Redistributions in binary form must reproduce the above copyright notice,
      this list of conditions and the following disclaimer in the documentation
      and/or other materials provided with the distribution.
  
   3. The end-user documentation included with the redistribution, if any, must
      include  the following  acknowledgment:  "This product includes  software
      developed  by the  Apache Software Foundation  (http://www.apache.org/)."
      Alternately, this  acknowledgment may  appear in the software itself,  if
      and wherever such third-party acknowledgments normally appear.
  
   4. The names "Apache Cocoon" and  "Apache Software Foundation" must  not  be
      used to  endorse or promote  products derived from  this software without
      prior written permission. For written permission, please contact
      [EMAIL PROTECTED]
  
   5. Products  derived from this software may not  be called "Apache", nor may
      "Apache" appear  in their name,  without prior written permission  of the
      Apache Software Foundation.
  
   THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
   INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
   FITNESS  FOR A PARTICULAR  PURPOSE ARE  DISCLAIMED.  IN NO  EVENT SHALL  THE
   APACHE SOFTWARE  FOUNDATION  OR ITS CONTRIBUTORS  BE LIABLE FOR  ANY DIRECT,
   INDIRECT, INCIDENTAL, SPECIAL,  EXEMPLARY, OR CONSEQUENTIAL  DAMAGES (INCLU-
   DING, BUT NOT LIMITED TO, PROCUREMENT  OF SUBSTITUTE GOODS OR SERVICES; LOSS
   OF USE, DATA, OR  PROFITS; OR BUSINESS  INTERRUPTION)  HOWEVER CAUSED AND ON
   ANY  THEORY OF LIABILITY,  WHETHER  IN CONTRACT,  STRICT LIABILITY,  OR TORT
   (INCLUDING  NEGLIGENCE OR  OTHERWISE) ARISING IN  ANY WAY OUT OF THE  USE OF
   THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  
   This software  consists of voluntary contributions made  by many individuals
   on  behalf of the Apache Software  Foundation and was  originally created by
   Stefano Mazzocchi  <[EMAIL PROTECTED]>. For more  information on the Apache
   Software Foundation, please see <http://www.apache.org/>.
  
  */
  package org.apache.cocoon.components.language.programming.java;
  
  import org.apache.avalon.excalibur.pool.Recyclable;
  import org.apache.cocoon.components.language.programming.CompilerError;
  import org.apache.cocoon.components.language.programming.LanguageCompiler;
  import org.apache.cocoon.util.ClassUtils;
  
  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;
  
  import java.io.BufferedOutputStream;
  import java.io.BufferedReader;
  import java.io.ByteArrayOutputStream;
  import java.io.File;
  import java.io.FileOutputStream;
  import java.io.FileReader;
  import java.io.IOException;
  import java.io.InputStream;
  import java.io.Reader;
  import java.util.HashMap;
  import java.util.LinkedList;
  import java.util.List;
  import java.util.Locale;
  import java.util.Map;
  import java.util.StringTokenizer;
  
  /**
   * Eclipse Java Compiler
   *
   * @version CVS $Id: EclipseJavaCompiler.java,v 1.1 2003/07/29 18:49:29 
vgritsenko Exp $
   */
  public class EclipseJavaCompiler implements LanguageCompiler, Recyclable {
  
      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;
          }
      }
  
      boolean debug;
  
      String sourceDir;
      String sourceFile; 
      String destDir;
      String sourceEncoding;
  
      List errors = new LinkedList();
  
  
      public EclipseJavaCompiler() {
          this.debug = true;
          source14 = true;
      }
  
      public void recycle() {
          sourceFile = null;
          sourceDir = null;
          destDir = null;
          sourceEncoding = null;
          errors.clear();
      }
  
      public void setFile(String file) {
          // This is the absolute path to the file to be compiled
          this.sourceFile = file;
      }
  
      public void setSource(String srcDir) {
          // This is the "sourcepath" of the file to be
          // compiled
          this.sourceDir = srcDir;
      }
  
      public void setDestination(String destDir) {
          // This is the output directory)
          this.destDir = destDir;
      }
  
      public void setEncoding(String encoding) {
          this.sourceEncoding = encoding; 
      }
  
      /**
       * Eclipse Java compiler ignores class path setting and uses current
       * Java class loader
       * @param cp classpath to be ignored
       */
      public void setClasspath(String cp) {
          // Not used 
      }
  
      private String makeClassName(String fileName) throws IOException {
          File origFile = new File(fileName);
          String canonical = null;
          if (origFile.exists()) {
              canonical = origFile.getCanonicalPath().replace('\\', '/');
          }
          String str = fileName;
          str = str.replace('\\', '/');
          if (sourceDir != null) {
              String prefix = 
                  new File(sourceDir).getCanonicalPath().replace('\\', '/');
              if (canonical != null) {
                  if (canonical.startsWith(prefix)) {
                      String result = canonical.substring(prefix.length() + 1,
                                                          canonical.length() 
-5);
                      result = result.replace('/', '.');
                      return result;
                  }
              } else {
                  File t = new File(sourceDir, fileName);
                  if (t.exists()) {
                      str = t.getCanonicalPath().replace('\\', '/');
                      String result = str.substring(prefix.length()+1,
                                                    str.length() - 
5).replace('/', '.');
                      return result;
                  }
              }
          }
          if (fileName.endsWith(".java")) {
              fileName = fileName.substring(0, fileName.length() - 5);
          }
          fileName = fileName.replace('\\', '.');
          return fileName.replace('/', '.');
      }
  
      public boolean compile() throws IOException {
          final String targetClassName = makeClassName(sourceFile);
          final ClassLoader classLoader = ClassUtils.getClassLoader();
          String[] fileNames = new String[] {sourceFile};
          String[] classNames = new String[] {targetClassName};
          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) {
                      handleError(className, -1, -1, 
                                  e.getMessage());
                      //e.printStackTrace();
                  }
                  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) {
                          handleError(className, -1, -1, 
                                      exc.getMessage());
                      } catch 
(org.eclipse.jdt.internal.compiler.classfmt.ClassFormatException exc) {
                          handleError(className, -1, -1, 
                                      exc.getMessage());
                      }
                      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 (sourceEncoding != null) {
              settings.put(CompilerOptions.OPTION_Encoding,
                           sourceEncoding);
          }
          if (debug) {
              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());
                                  handleError(name,
                                              problem.getSourceLineNumber(),
                                              -1,
                                              problem.getMessage());
                              }
                          } 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 = destDir + "/" + 
                                      className.replace('.', '/') + ".class";
                                  FileOutputStream fout = 
                                      new FileOutputStream(outFile);
                                  BufferedOutputStream bos = 
                                      new BufferedOutputStream(fout);
                                  bos.write(bytes);
                                  bos.close();
                              }
                          }
                      } catch (IOException exc) {
                          exc.printStackTrace();
                      }
                  }
              };
          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);
          return errors.size() == 0;
      }
  
      void handleError(String className, int line, int column, Object 
errorMessage) {
          String fileName = 
              className.replace('.', File.separatorChar) + ".java";
          if (column < 0) column = 0;
          errors.add(new CompilerError(fileName,
                                       true,
                                       line,
                                       column,
                                       line,
                                       column,
                                       errorMessage.toString()));
      }
  
      public List getErrors() throws IOException {
          return errors;
      }
  }
  
  
  

Reply via email to