Package org.tempuri.javacImpl.eclipse

Source Code of org.tempuri.javacImpl.eclipse.JavaCompilerImpl

/*
Copyright (c) 2002 Christopher Oliver

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
package org.tempuri.javacImpl.eclipse;
import org.eclipse.jdt.core.compiler.IProblem;
import org.eclipse.jdt.internal.compiler.env.INameEnvironment;
import org.eclipse.jdt.internal.compiler.env.NameEnvironmentAnswer;
import org.eclipse.jdt.internal.compiler.ClassFile;
import org.eclipse.jdt.internal.compiler.Compiler;
import org.eclipse.jdt.internal.compiler.DefaultErrorHandlingPolicies;
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.ICompilerRequestor;
import org.eclipse.jdt.internal.compiler.CompilationResult;
import org.eclipse.jdt.internal.compiler.problem.DefaultProblem;
import org.eclipse.jdt.internal.compiler.problem.DefaultProblemFactory;
import org.eclipse.jdt.internal.compiler.impl.CompilerOptions;
import org.tempuri.javac.*;
import java.io.InputStream;
import java.io.ByteArrayInputStream;
import java.io.OutputStream;
import java.io.ByteArrayOutputStream;
import java.io.Reader;
import java.io.Writer;
import java.io.PrintStream;
import java.io.IOException;
import java.util.Locale;
import java.util.Map;
import java.util.HashMap;
import java.util.Iterator;
import java.util.StringTokenizer;

/**
* Implementation of JavaCompiler with eclipse.org Java Development
* Tools compiler
*/

public class JavaCompilerImpl implements JavaCompiler {

    public JavaCompilerImpl() {
    }

    boolean target14 = false;
    boolean source14 = false;
    boolean debug = true;
    String sourceEncoding;

    final static String[] versions = new String[] {"1.1", "1.2", "1.3"};

    static void checkVersion(String version,
                             String errorMessage)
        throws IllegalArgumentException {
        for (int i = 0; i < versions.length; i++) {
            if (versions[i].equals(version)) {
                return;
            }
        }
        throw new IllegalArgumentException(errorMessage);
    }

    public void setTargetVersion(String targetVersion)
        throws IllegalArgumentException {
        if (targetVersion.equals("1.4")) {
            target14 = true;
        } else {
            checkVersion(targetVersion,
                         "illegal target release: "+targetVersion);
            target14 = false;
        }
           
    }

    public void setSourceEncoding(String encoding) {
  this.sourceEncoding = encoding;
    }

    public void setDebug(boolean value) {
        debug = true;
    }

    public void setSourceVersion(String sourceVersion)
        throws IllegalArgumentException {
        if (sourceVersion.equals("1.4")) {
            source14 = true;
        } else {
            checkVersion(sourceVersion,
                         "illegal source release: "+sourceVersion);
            source14 = false;
        }
    }

    static public String makeClassName(String name) {
        if (name.endsWith(".java")) {
            name = name.substring(0, name.length() - 5);
        } else if (name.endsWith(".class")) {
            name = name.substring(0, name.length() - 6);
        }
        name = name.replace('\\', '.');
        name = name.replace('/', '.');
        return name;
    }

    public void compile(final String[] classNames,
                        final JavaSourceReaderFactory sourceReaderFactory,
                        final JavaClassReaderFactory classReaderFactory,
                        final JavaClassWriterFactory classWriterFactory,
                        final JavaCompilerErrorHandler errorHandler) {

        class CompilationUnit implements ICompilationUnit {

            String className;

            CompilationUnit(String className) {
                this.className = className;
            }

            public char[] getFileName() {
                return className.toCharArray();
            }
           
            public char[] getContents() {
                char[] result = null;
                try {
                    JavaSourceReader sourceReader =
                        sourceReaderFactory.getSourceReader(className);
                    if (sourceReader == null) {
                        return null;
                    }
                    Reader reader = sourceReader.getReader();
                    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) {
        errorHandler.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 {
                        JavaSourceReader sourceReader =
                            sourceReaderFactory.getSourceReader(className);
                        if (sourceReader != null) {
                            ICompilationUnit compilationUnit =
                                new CompilationUnit(className);
                            return
                                new NameEnvironmentAnswer(compilationUnit);
                        }
                        JavaClassReader classReader =
                            classReaderFactory.getClassReader(className);
                        if (classReader != null) {
                            byte[] classBytes;
                            byte[] buf = new byte[8192];
                            ByteArrayOutputStream baos =
                                new ByteArrayOutputStream(buf.length);
                            int count;
                            InputStream is = classReader.getInputStream();
                            while ((count = is.read(buf, 0, buf.length)) > 0) {
                                baos.write(buf, 0, count);
                            }
                            baos.flush();
                            classBytes = baos.toByteArray();
                            char[] fileName =
                                classReader.getClassName().toCharArray();
                            ClassFileReader classFileReader =
                                new ClassFileReader(classBytes, fileName,
                                                    true);
                            return
                                new NameEnvironmentAnswer(classFileReader);
                        }
                    } catch (IOException exc) {
      errorHandler.handleError(className, -1, -1,
             exc.getMessage());
                    } catch (org.eclipse.jdt.internal.compiler.classfmt.ClassFormatException exc) {
      errorHandler.handleError(className, -1, -1,
             exc.getMessage());
                    }
                    return null;
                }

    private boolean isPackage(String result) {
                    JavaClassReader classReader = null;
                    try {
                        classReader =
                            classReaderFactory.getClassReader(result);
                    } catch (IOException exc) {
      errorHandler.handleError(result, -1, -1,
             exc.getMessage());
                    }
                    if (classReader == null) {
                        JavaSourceReader sourceReader = null;
                        try {
                            sourceReader =
                                sourceReaderFactory.getSourceReader(result);
                        } catch (IOException exc) {
          errorHandler.handleError(result, -1, -1,
                 exc.getMessage());
                        }
                        if (sourceReader == null) {
                            return true;
                        }
                    }
                    return false;
    }

                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());
                                errorHandler.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 = ".";
                                }
                                JavaClassWriter writer =
                                    classWriterFactory.getClassWriter(className);
                                byte[] bytes = classFile.getBytes();
                                ByteArrayInputStream bais =
                                    new ByteArrayInputStream(bytes);
                                writer.writeClass(bais);
                            }
                        }
                    } 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(className);
        }
        Compiler compiler = new Compiler(env,
                                         policy,
                                         settings,
                                         requestor,
                                         problemFactory);
        compiler.compile(compilationUnits);
    }
}
TOP

Related Classes of org.tempuri.javacImpl.eclipse.JavaCompilerImpl

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.