Search in sources :

Example 1 with IProblemFactory

use of org.eclipse.jdt.internal.compiler.IProblemFactory in project che by eclipse.

the class SourceMapper method mapSource.

/**
     * Maps the given source code to the given binary type and its children.
     * If a non-null java element is passed, finds the name range for the
     * given java element without storing it.
     */
public synchronized ISourceRange mapSource(IType type, char[] contents, IBinaryType info, IJavaElement elementToFind) {
    this.binaryType = (BinaryType) type;
    // check whether it is already mapped
    if (this.sourceRanges.get(type) != null)
        return (elementToFind != null) ? getNameRange(elementToFind) : null;
    this.importsTable.remove(this.binaryType);
    this.importsCounterTable.remove(this.binaryType);
    this.searchedElement = elementToFind;
    this.types = new IType[1];
    this.typeDeclarationStarts = new int[1];
    this.typeNameRanges = new SourceRange[1];
    this.typeModifiers = new int[1];
    this.typeDepth = -1;
    this.memberDeclarationStart = new int[1];
    this.memberName = new String[1];
    this.memberNameRange = new SourceRange[1];
    this.methodParameterTypes = new char[1][][];
    this.methodParameterNames = new char[1][][];
    this.anonymousCounter = 0;
    HashMap oldSourceRanges = null;
    if (elementToFind != null) {
        oldSourceRanges = (HashMap) this.sourceRanges.clone();
    }
    try {
        IProblemFactory factory = new DefaultProblemFactory();
        SourceElementParser parser = null;
        this.anonymousClassName = 0;
        if (info == null) {
            try {
                info = (IBinaryType) this.binaryType.getElementInfo();
            } catch (JavaModelException e) {
                return null;
            }
        }
        boolean isAnonymousClass = info.isAnonymous();
        char[] fullName = info.getName();
        if (isAnonymousClass) {
            String eltName = this.binaryType.getParent().getElementName();
            eltName = eltName.substring(eltName.lastIndexOf('$') + 1, eltName.length());
            try {
                this.anonymousClassName = Integer.parseInt(eltName);
            } catch (NumberFormatException e) {
            // ignore
            }
        }
        boolean doFullParse = hasToRetrieveSourceRangesForLocalClass(fullName);
        parser = new SourceElementParser(this, factory, new CompilerOptions(this.options), doFullParse, true);
        // disable javadoc parsing
        parser.javadocParser.checkDocComment = false;
        IJavaElement javaElement = this.binaryType.getCompilationUnit();
        if (javaElement == null)
            javaElement = this.binaryType.getParent();
        parser.parseCompilationUnit(new BasicCompilationUnit(contents, null, this.binaryType.sourceFileName(info), javaElement), doFullParse, null);
        if (elementToFind != null) {
            ISourceRange range = getNameRange(elementToFind);
            return range;
        } else {
            return null;
        }
    } finally {
        if (elementToFind != null) {
            this.sourceRanges = oldSourceRanges;
        }
        this.binaryType = null;
        this.searchedElement = null;
        this.types = null;
        this.typeDeclarationStarts = null;
        this.typeNameRanges = null;
        this.typeDepth = -1;
    }
}
Also used : IJavaElement(org.eclipse.jdt.core.IJavaElement) JavaModelException(org.eclipse.jdt.core.JavaModelException) HashMap(java.util.HashMap) BasicCompilationUnit(org.eclipse.jdt.internal.core.BasicCompilationUnit) SourceElementParser(org.eclipse.jdt.internal.compiler.SourceElementParser) CompilerOptions(org.eclipse.jdt.internal.compiler.impl.CompilerOptions) DefaultProblemFactory(org.eclipse.jdt.internal.compiler.problem.DefaultProblemFactory) IProblemFactory(org.eclipse.jdt.internal.compiler.IProblemFactory) ISourceRange(org.eclipse.jdt.core.ISourceRange)

Example 2 with IProblemFactory

use of org.eclipse.jdt.internal.compiler.IProblemFactory in project tomcat70 by apache.

the class JDTCompiler method generateClass.

/**
 * Compile the servlet from .java file to .class file
 */
@Override
protected void generateClass(String[] smap) throws FileNotFoundException, JasperException, Exception {
    long t1 = 0;
    if (log.isDebugEnabled()) {
        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 = ctxt.getJspLoader();
    String[] fileNames = new String[] { sourceFile };
    String[] classNames = new String[] { targetClassName };
    final ArrayList<JavacErrorDetail> problemList = new ArrayList<JavacErrorDetail>();
    class CompilationUnit implements ICompilationUnit {

        private final String className;

        private final String sourceFile;

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

        @Override
        public char[] getFileName() {
            return sourceFile.toCharArray();
        }

        @Override
        public char[] getContents() {
            char[] result = null;
            FileInputStream is = null;
            InputStreamReader isr = null;
            Reader reader = null;
            try {
                is = new FileInputStream(sourceFile);
                isr = new InputStreamReader(is, ctxt.getOptions().getJavaEncoding());
                reader = new BufferedReader(isr);
                char[] chars = new char[8192];
                StringBuilder buf = new StringBuilder();
                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);
            } finally {
                if (reader != null) {
                    try {
                        reader.close();
                    } catch (IOException ioe) {
                    /*Ignore*/
                    }
                }
                if (isr != null) {
                    try {
                        isr.close();
                    } catch (IOException ioe) {
                    /*Ignore*/
                    }
                }
                if (is != null) {
                    try {
                        is.close();
                    } catch (IOException exc) {
                    /*Ignore*/
                    }
                }
            }
            return result;
        }

        @Override
        public char[] getMainTypeName() {
            int dot = className.lastIndexOf('.');
            if (dot > 0) {
                return className.substring(dot + 1).toCharArray();
            }
            return className.toCharArray();
        }

        @Override
        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;
        }

        @Override
        public boolean ignoreOptionalProblems() {
            return false;
        }
    }
    final INameEnvironment env = new INameEnvironment() {

        @Override
        public NameEnvironmentAnswer findType(char[][] compoundTypeName) {
            StringBuilder result = new StringBuilder();
            String sep = "";
            for (int i = 0; i < compoundTypeName.length; i++) {
                result.append(sep);
                result.append(compoundTypeName[i]);
                sep = ".";
            }
            return findType(result.toString());
        }

        @Override
        public NameEnvironmentAnswer findType(char[] typeName, char[][] packageName) {
            StringBuilder result = new StringBuilder();
            String sep = "";
            for (int i = 0; i < packageName.length; i++) {
                result.append(sep);
                result.append(packageName[i]);
                sep = ".";
            }
            result.append(sep);
            result.append(typeName);
            return findType(result.toString());
        }

        private NameEnvironmentAnswer findType(String className) {
            InputStream is = null;
            try {
                if (className.equals(targetClassName)) {
                    ICompilationUnit compilationUnit = new CompilationUnit(sourceFile, className);
                    return new NameEnvironmentAnswer(compilationUnit, null);
                }
                String resourceName = className.replace('.', '/') + ".class";
                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, null);
                }
            } catch (IOException exc) {
                log.error("Compilation error", exc);
            } catch (org.eclipse.jdt.internal.compiler.classfmt.ClassFormatException exc) {
                log.error("Compilation error", exc);
            } finally {
                if (is != null) {
                    try {
                        is.close();
                    } catch (IOException exc) {
                    // Ignore
                    }
                }
            }
            return null;
        }

        private boolean isPackage(String result) {
            if (result.equals(targetClassName)) {
                return false;
            }
            String resourceName = result.replace('.', '/') + ".class";
            InputStream is = null;
            try {
                is = classLoader.getResourceAsStream(resourceName);
                return is == null;
            } finally {
                if (is != null) {
                    try {
                        is.close();
                    } catch (IOException e) {
                    }
                }
            }
        }

        @Override
        public boolean isPackage(char[][] parentPackageName, char[] packageName) {
            StringBuilder result = new StringBuilder();
            String sep = "";
            if (parentPackageName != null) {
                for (int i = 0; i < parentPackageName.length; i++) {
                    result.append(sep);
                    result.append(parentPackageName[i]);
                    sep = ".";
                }
            }
            if (Character.isUpperCase(packageName[0])) {
                if (!isPackage(result.toString())) {
                    return false;
                }
            }
            result.append(sep);
            result.append(packageName);
            return isPackage(result.toString());
        }

        @Override
        public void cleanup() {
        }
    };
    final IErrorHandlingPolicy policy = DefaultErrorHandlingPolicies.proceedWithAllProblems();
    final Map<String, String> settings = new HashMap<String, String>();
    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);
    }
    // Source JVM
    if (ctxt.getOptions().getCompilerSourceVM() != null) {
        String opt = ctxt.getOptions().getCompilerSourceVM();
        if (opt.equals("1.1")) {
            settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_1);
        } else if (opt.equals("1.2")) {
            settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_2);
        } else if (opt.equals("1.3")) {
            settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_3);
        } else if (opt.equals("1.4")) {
            settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_4);
        } else if (opt.equals("1.5")) {
            settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_5);
        } else if (opt.equals("1.6")) {
            settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_6);
        } else if (opt.equals("1.7")) {
            settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_7);
        } else if (opt.equals("1.8")) {
            settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_8);
        } else if (opt.equals("1.9")) {
            settings.put(CompilerOptions.OPTION_Source, // CompilerOptions.VERSION_1_9
            "1.9");
        } else {
            log.warn("Unknown source VM " + opt + " ignored.");
            settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_6);
        }
    } else {
        // Default to 1.6
        settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_6);
    }
    // Target JVM
    if (ctxt.getOptions().getCompilerTargetVM() != null) {
        String opt = ctxt.getOptions().getCompilerTargetVM();
        if (opt.equals("1.1")) {
            settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_1);
        } else if (opt.equals("1.2")) {
            settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_2);
        } else if (opt.equals("1.3")) {
            settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_3);
        } else if (opt.equals("1.4")) {
            settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_4);
        } else if (opt.equals("1.5")) {
            settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_5);
            settings.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_1_5);
        } else if (opt.equals("1.6")) {
            settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_6);
            settings.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_1_6);
        } else if (opt.equals("1.7")) {
            settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_7);
            settings.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_1_7);
        } else if (opt.equals("1.8")) {
            settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_8);
            settings.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_1_8);
        } else if (opt.equals("1.9")) {
            settings.put(CompilerOptions.OPTION_TargetPlatform, // CompilerOptions.VERSION_1_9
            "1.9");
            settings.put(CompilerOptions.OPTION_Compliance, // CompilerOptions.VERSION_1_9
            "1.9");
        } else {
            log.warn("Unknown target VM " + opt + " ignored.");
            settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_6);
        }
    } else {
        // Default to 1.6
        settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_6);
        settings.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_1_6);
    }
    final IProblemFactory problemFactory = new DefaultProblemFactory(Locale.getDefault());
    final ICompilerRequestor requestor = new ICompilerRequestor() {

        @Override
        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];
                        if (problem.isError()) {
                            String name = new String(problems[i].getOriginatingFileName());
                            try {
                                problemList.add(ErrorDispatcher.createJavacError(name, pageNodes, new StringBuilder(problem.getMessage()), problem.getSourceLineNumber(), ctxt));
                            } catch (JasperException e) {
                                log.error("Error visiting node", e);
                            }
                        }
                    }
                }
                if (problemList.isEmpty()) {
                    ClassFile[] classFiles = result.getClassFiles();
                    for (int i = 0; i < classFiles.length; i++) {
                        ClassFile classFile = classFiles[i];
                        char[][] compoundName = classFile.getCompoundName();
                        StringBuilder classFileName = new StringBuilder(outputDir).append('/');
                        for (int j = 0; j < compoundName.length; j++) {
                            if (j > 0) {
                                classFileName.append('/');
                            }
                            classFileName.append(compoundName[j]);
                        }
                        byte[] bytes = classFile.getBytes();
                        classFileName.append(".class");
                        FileOutputStream fout = null;
                        BufferedOutputStream bos = null;
                        try {
                            fout = new FileOutputStream(classFileName.toString());
                            bos = new BufferedOutputStream(fout);
                            bos.write(bytes);
                        } finally {
                            if (bos != null) {
                                try {
                                    bos.close();
                                } catch (IOException e) {
                                }
                            }
                        }
                    }
                }
            } 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);
    }
    CompilerOptions cOptions = new CompilerOptions(settings);
    cOptions.parseLiteralExpressionsAsConstants = true;
    Compiler compiler = new Compiler(env, policy, cOptions, requestor, problemFactory);
    compiler.compile(compilationUnits);
    if (!ctxt.keepGenerated()) {
        File javaFile = new File(ctxt.getServletJavaFileName());
        javaFile.delete();
    }
    if (!problemList.isEmpty()) {
        JavacErrorDetail[] jeds = problemList.toArray(new JavacErrorDetail[0]);
        errDispatcher.javacError(jeds);
    }
    if (log.isDebugEnabled()) {
        long t2 = System.currentTimeMillis();
        log.debug("Compiled " + ctxt.getServletJavaFileName() + " " + (t2 - t1) + "ms");
    }
    if (ctxt.isPrototypeMode()) {
        return;
    }
    // JSR45 Support
    if (!options.isSmapSuppressed()) {
        SmapUtil.installSmap(smap);
    }
}
Also used : IErrorHandlingPolicy(org.eclipse.jdt.internal.compiler.IErrorHandlingPolicy) NameEnvironmentAnswer(org.eclipse.jdt.internal.compiler.env.NameEnvironmentAnswer) HashMap(java.util.HashMap) ClassFileReader(org.eclipse.jdt.internal.compiler.classfmt.ClassFileReader) ArrayList(java.util.ArrayList) ClassFileReader(org.eclipse.jdt.internal.compiler.classfmt.ClassFileReader) Reader(java.io.Reader) InputStreamReader(java.io.InputStreamReader) BufferedReader(java.io.BufferedReader) JasperException(org.apache.jasper.JasperException) INameEnvironment(org.eclipse.jdt.internal.compiler.env.INameEnvironment) DefaultProblemFactory(org.eclipse.jdt.internal.compiler.problem.DefaultProblemFactory) BufferedOutputStream(java.io.BufferedOutputStream) IProblemFactory(org.eclipse.jdt.internal.compiler.IProblemFactory) ICompilationUnit(org.eclipse.jdt.internal.compiler.env.ICompilationUnit) ICompilationUnit(org.eclipse.jdt.internal.compiler.env.ICompilationUnit) Compiler(org.eclipse.jdt.internal.compiler.Compiler) ClassFile(org.eclipse.jdt.internal.compiler.ClassFile) InputStreamReader(java.io.InputStreamReader) ICompilerRequestor(org.eclipse.jdt.internal.compiler.ICompilerRequestor) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) IOException(java.io.IOException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IProblem(org.eclipse.jdt.core.compiler.IProblem) FileInputStream(java.io.FileInputStream) StringTokenizer(java.util.StringTokenizer) FileOutputStream(java.io.FileOutputStream) BufferedReader(java.io.BufferedReader) CompilerOptions(org.eclipse.jdt.internal.compiler.impl.CompilerOptions) CompilationResult(org.eclipse.jdt.internal.compiler.CompilationResult) ClassFile(org.eclipse.jdt.internal.compiler.ClassFile) File(java.io.File)

Example 3 with IProblemFactory

use of org.eclipse.jdt.internal.compiler.IProblemFactory in project tomcat by apache.

the class JDTCompiler method generateClass.

/**
 * Compile the servlet from .java file to .class file
 */
@Override
protected void generateClass(Map<String, SmapStratum> smaps) throws FileNotFoundException, JasperException, Exception {
    long t1 = 0;
    if (log.isDebugEnabled()) {
        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 = ctxt.getJspLoader();
    String[] fileNames = new String[] { sourceFile };
    String[] classNames = new String[] { targetClassName };
    final List<JavacErrorDetail> problemList = new ArrayList<>();
    class CompilationUnit implements ICompilationUnit {

        private final String className;

        private final String sourceFile;

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

        @Override
        public char[] getFileName() {
            return sourceFile.toCharArray();
        }

        @Override
        public char[] getContents() {
            char[] result = null;
            try (FileInputStream is = new FileInputStream(sourceFile);
                InputStreamReader isr = new InputStreamReader(is, ctxt.getOptions().getJavaEncoding());
                Reader reader = new BufferedReader(isr)) {
                char[] chars = new char[8192];
                StringBuilder buf = new StringBuilder();
                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(Localizer.getMessage("jsp.error.compilation.source", sourceFile), e);
            }
            return result;
        }

        @Override
        public char[] getMainTypeName() {
            int dot = className.lastIndexOf('.');
            if (dot > 0) {
                return className.substring(dot + 1).toCharArray();
            }
            return className.toCharArray();
        }

        @Override
        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;
        }

        @Override
        public boolean ignoreOptionalProblems() {
            return false;
        }
    }
    final INameEnvironment env = new INameEnvironment() {

        @Override
        public NameEnvironmentAnswer findType(char[][] compoundTypeName) {
            StringBuilder result = new StringBuilder();
            for (int i = 0; i < compoundTypeName.length; i++) {
                if (i > 0) {
                    result.append('.');
                }
                result.append(compoundTypeName[i]);
            }
            return findType(result.toString());
        }

        @Override
        public NameEnvironmentAnswer findType(char[] typeName, char[][] packageName) {
            StringBuilder result = new StringBuilder();
            int i = 0;
            for (; i < packageName.length; i++) {
                if (i > 0) {
                    result.append('.');
                }
                result.append(packageName[i]);
            }
            if (i > 0) {
                result.append('.');
            }
            result.append(typeName);
            return findType(result.toString());
        }

        private NameEnvironmentAnswer findType(String className) {
            if (className.equals(targetClassName)) {
                ICompilationUnit compilationUnit = new CompilationUnit(sourceFile, className);
                return new NameEnvironmentAnswer(compilationUnit, null);
            }
            String resourceName = className.replace('.', '/') + ".class";
            try (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, null);
                }
            } catch (IOException | ClassFormatException exc) {
                log.error(Localizer.getMessage("jsp.error.compilation.dependent", className), exc);
            }
            return null;
        }

        private boolean isPackage(String result) {
            if (result.equals(targetClassName) || result.startsWith(targetClassName + '$')) {
                return false;
            }
            String resourceName = result.replace('.', '/') + ".class";
            try (InputStream is = classLoader.getResourceAsStream(resourceName)) {
                return is == null;
            } catch (IOException e) {
                // we are here, since close on is failed. That means it was not null
                return false;
            }
        }

        @Override
        public boolean isPackage(char[][] parentPackageName, char[] packageName) {
            StringBuilder result = new StringBuilder();
            int i = 0;
            if (parentPackageName != null) {
                for (; i < parentPackageName.length; i++) {
                    if (i > 0) {
                        result.append('.');
                    }
                    result.append(parentPackageName[i]);
                }
            }
            if (Character.isUpperCase(packageName[0])) {
                if (!isPackage(result.toString())) {
                    return false;
                }
            }
            if (i > 0) {
                result.append('.');
            }
            result.append(packageName);
            return isPackage(result.toString());
        }

        @Override
        public void cleanup() {
        }
    };
    final IErrorHandlingPolicy policy = DefaultErrorHandlingPolicies.proceedWithAllProblems();
    final Map<String, String> 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);
    }
    // Source JVM
    if (ctxt.getOptions().getCompilerSourceVM() != null) {
        String opt = ctxt.getOptions().getCompilerSourceVM();
        if (opt.equals("1.1")) {
            settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_1);
        } else if (opt.equals("1.2")) {
            settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_2);
        } else if (opt.equals("1.3")) {
            settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_3);
        } else if (opt.equals("1.4")) {
            settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_4);
        } else if (opt.equals("1.5")) {
            settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_5);
        } else if (opt.equals("1.6")) {
            settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_6);
        } else if (opt.equals("1.7")) {
            settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_7);
        } else if (opt.equals("1.8")) {
            settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_8);
        // Version format changed from Java 9 onwards.
        // Support old format that was used in EA implementation as well
        } else if (opt.equals("9") || opt.equals("1.9")) {
            settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_9);
        } else if (opt.equals("10")) {
            settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_10);
        } else if (opt.equals("11")) {
            settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_11);
        } else if (opt.equals("12")) {
            settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_12);
        } else if (opt.equals("13")) {
            settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_13);
        } else if (opt.equals("14")) {
            settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_14);
        } else if (opt.equals("15")) {
            settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_15);
        } else if (opt.equals("16")) {
            settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_16);
        } else if (opt.equals("17")) {
            settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_17);
        } else if (opt.equals("18")) {
            // Constant not available in latest ECJ version shipped with
            // Tomcat. May be supported in a snapshot build.
            // This is checked against the actual version below.
            settings.put(CompilerOptions.OPTION_Source, "18");
        } else {
            log.warn(Localizer.getMessage("jsp.warning.unknown.sourceVM", opt));
            settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_11);
        }
    } else {
        // Default to 11
        settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_11);
    }
    // Target JVM
    if (ctxt.getOptions().getCompilerTargetVM() != null) {
        String opt = ctxt.getOptions().getCompilerTargetVM();
        if (opt.equals("1.1")) {
            settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_1);
        } else if (opt.equals("1.2")) {
            settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_2);
        } else if (opt.equals("1.3")) {
            settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_3);
        } else if (opt.equals("1.4")) {
            settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_4);
        } else if (opt.equals("1.5")) {
            settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_5);
            settings.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_1_5);
        } else if (opt.equals("1.6")) {
            settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_6);
            settings.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_1_6);
        } else if (opt.equals("1.7")) {
            settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_7);
            settings.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_1_7);
        } else if (opt.equals("1.8")) {
            settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_8);
            settings.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_1_8);
        // Version format changed from Java 9 onwards.
        // Support old format that was used in EA implementation as well
        } else if (opt.equals("9") || opt.equals("1.9")) {
            settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_9);
            settings.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_9);
        } else if (opt.equals("10")) {
            settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_10);
            settings.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_10);
        } else if (opt.equals("11")) {
            settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_11);
            settings.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_11);
        } else if (opt.equals("12")) {
            settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_12);
            settings.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_12);
        } else if (opt.equals("13")) {
            settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_13);
            settings.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_13);
        } else if (opt.equals("14")) {
            settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_14);
            settings.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_14);
        } else if (opt.equals("15")) {
            settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_15);
            settings.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_15);
        } else if (opt.equals("16")) {
            settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_16);
            settings.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_16);
        } else if (opt.equals("17")) {
            settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_17);
            settings.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_17);
        } else if (opt.equals("18")) {
            // Constant not available in latest ECJ version shipped with
            // Tomcat. May be supported in a snapshot build.
            // This is checked against the actual version below.
            settings.put(CompilerOptions.OPTION_TargetPlatform, "18");
            settings.put(CompilerOptions.OPTION_Compliance, "18");
        } else {
            log.warn(Localizer.getMessage("jsp.warning.unknown.targetVM", opt));
            settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_11);
        }
    } else {
        // Default to 11
        settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_11);
        settings.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_11);
    }
    final IProblemFactory problemFactory = new DefaultProblemFactory(Locale.getDefault());
    final ICompilerRequestor requestor = new ICompilerRequestor() {

        @Override
        public void acceptResult(CompilationResult result) {
            try {
                if (result.hasProblems()) {
                    IProblem[] problems = result.getProblems();
                    for (IProblem problem : problems) {
                        if (problem.isError()) {
                            String name = new String(problem.getOriginatingFileName());
                            try {
                                problemList.add(ErrorDispatcher.createJavacError(name, pageNodes, new StringBuilder(problem.getMessage()), problem.getSourceLineNumber(), ctxt));
                            } catch (JasperException e) {
                                log.error(Localizer.getMessage("jsp.error.compilation.jdtProblemError"), e);
                            }
                        }
                    }
                }
                if (problemList.isEmpty()) {
                    ClassFile[] classFiles = result.getClassFiles();
                    for (ClassFile classFile : classFiles) {
                        char[][] compoundName = classFile.getCompoundName();
                        StringBuilder classFileName = new StringBuilder(outputDir).append('/');
                        for (int j = 0; j < compoundName.length; j++) {
                            if (j > 0) {
                                classFileName.append('/');
                            }
                            classFileName.append(compoundName[j]);
                        }
                        byte[] bytes = classFile.getBytes();
                        classFileName.append(".class");
                        try (FileOutputStream fout = new FileOutputStream(classFileName.toString());
                            BufferedOutputStream bos = new BufferedOutputStream(fout)) {
                            bos.write(bytes);
                        }
                    }
                }
            } catch (IOException exc) {
                log.error(Localizer.getMessage("jsp.error.compilation.jdt"), 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);
    }
    CompilerOptions cOptions = new CompilerOptions(settings);
    // Check source/target JDK versions as the newest versions are allowed
    // in Tomcat configuration but may not be supported by the ECJ version
    // being used.
    String requestedSource = ctxt.getOptions().getCompilerSourceVM();
    if (requestedSource != null) {
        String actualSource = CompilerOptions.versionFromJdkLevel(cOptions.sourceLevel);
        if (!requestedSource.equals(actualSource)) {
            log.warn(Localizer.getMessage("jsp.warning.unsupported.sourceVM", requestedSource, actualSource));
        }
    }
    String requestedTarget = ctxt.getOptions().getCompilerTargetVM();
    if (requestedTarget != null) {
        String actualTarget = CompilerOptions.versionFromJdkLevel(cOptions.targetJDK);
        if (!requestedTarget.equals(actualTarget)) {
            log.warn(Localizer.getMessage("jsp.warning.unsupported.targetVM", requestedTarget, actualTarget));
        }
    }
    cOptions.parseLiteralExpressionsAsConstants = true;
    Compiler compiler = new Compiler(env, policy, cOptions, requestor, problemFactory);
    compiler.compile(compilationUnits);
    if (!ctxt.keepGenerated()) {
        File javaFile = new File(ctxt.getServletJavaFileName());
        if (!javaFile.delete()) {
            throw new JasperException(Localizer.getMessage("jsp.warning.compiler.javafile.delete.fail", javaFile));
        }
    }
    if (!problemList.isEmpty()) {
        JavacErrorDetail[] jeds = problemList.toArray(new JavacErrorDetail[0]);
        errDispatcher.javacError(jeds);
    }
    if (log.isDebugEnabled()) {
        long t2 = System.currentTimeMillis();
        log.debug("Compiled " + ctxt.getServletJavaFileName() + " " + (t2 - t1) + "ms");
    }
    if (ctxt.isPrototypeMode()) {
        return;
    }
    // JSR45 Support
    if (!options.isSmapSuppressed()) {
        SmapUtil.installSmap(smaps);
    }
}
Also used : IErrorHandlingPolicy(org.eclipse.jdt.internal.compiler.IErrorHandlingPolicy) NameEnvironmentAnswer(org.eclipse.jdt.internal.compiler.env.NameEnvironmentAnswer) HashMap(java.util.HashMap) ClassFileReader(org.eclipse.jdt.internal.compiler.classfmt.ClassFileReader) ArrayList(java.util.ArrayList) ClassFileReader(org.eclipse.jdt.internal.compiler.classfmt.ClassFileReader) Reader(java.io.Reader) InputStreamReader(java.io.InputStreamReader) BufferedReader(java.io.BufferedReader) ClassFormatException(org.eclipse.jdt.internal.compiler.classfmt.ClassFormatException) JasperException(org.apache.jasper.JasperException) INameEnvironment(org.eclipse.jdt.internal.compiler.env.INameEnvironment) DefaultProblemFactory(org.eclipse.jdt.internal.compiler.problem.DefaultProblemFactory) BufferedOutputStream(java.io.BufferedOutputStream) IProblemFactory(org.eclipse.jdt.internal.compiler.IProblemFactory) ICompilationUnit(org.eclipse.jdt.internal.compiler.env.ICompilationUnit) ICompilationUnit(org.eclipse.jdt.internal.compiler.env.ICompilationUnit) Compiler(org.eclipse.jdt.internal.compiler.Compiler) ClassFile(org.eclipse.jdt.internal.compiler.ClassFile) InputStreamReader(java.io.InputStreamReader) ICompilerRequestor(org.eclipse.jdt.internal.compiler.ICompilerRequestor) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) IOException(java.io.IOException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IProblem(org.eclipse.jdt.core.compiler.IProblem) FileInputStream(java.io.FileInputStream) StringTokenizer(java.util.StringTokenizer) FileOutputStream(java.io.FileOutputStream) BufferedReader(java.io.BufferedReader) CompilerOptions(org.eclipse.jdt.internal.compiler.impl.CompilerOptions) CompilationResult(org.eclipse.jdt.internal.compiler.CompilationResult) ClassFile(org.eclipse.jdt.internal.compiler.ClassFile) File(java.io.File)

Example 4 with IProblemFactory

use of org.eclipse.jdt.internal.compiler.IProblemFactory in project tomcat by apache.

the class JDTCompiler method generateClass.

/**
     * Compile the servlet from .java file to .class file
     */
@Override
protected void generateClass(String[] smap) throws FileNotFoundException, JasperException, Exception {
    long t1 = 0;
    if (log.isDebugEnabled()) {
        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 = ctxt.getJspLoader();
    String[] fileNames = new String[] { sourceFile };
    String[] classNames = new String[] { targetClassName };
    final ArrayList<JavacErrorDetail> problemList = new ArrayList<>();
    class CompilationUnit implements ICompilationUnit {

        private final String className;

        private final String sourceFile;

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

        @Override
        public char[] getFileName() {
            return sourceFile.toCharArray();
        }

        @Override
        public char[] getContents() {
            char[] result = null;
            try (FileInputStream is = new FileInputStream(sourceFile);
                InputStreamReader isr = new InputStreamReader(is, ctxt.getOptions().getJavaEncoding());
                Reader reader = new BufferedReader(isr)) {
                char[] chars = new char[8192];
                StringBuilder buf = new StringBuilder();
                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;
        }

        @Override
        public char[] getMainTypeName() {
            int dot = className.lastIndexOf('.');
            if (dot > 0) {
                return className.substring(dot + 1).toCharArray();
            }
            return className.toCharArray();
        }

        @Override
        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;
        }

        @Override
        public boolean ignoreOptionalProblems() {
            return false;
        }
    }
    final INameEnvironment env = new INameEnvironment() {

        @Override
        public NameEnvironmentAnswer findType(char[][] compoundTypeName) {
            StringBuilder result = new StringBuilder();
            for (int i = 0; i < compoundTypeName.length; i++) {
                if (i > 0)
                    result.append('.');
                result.append(compoundTypeName[i]);
            }
            return findType(result.toString());
        }

        @Override
        public NameEnvironmentAnswer findType(char[] typeName, char[][] packageName) {
            StringBuilder result = new StringBuilder();
            int i = 0;
            for (; i < packageName.length; i++) {
                if (i > 0)
                    result.append('.');
                result.append(packageName[i]);
            }
            if (i > 0)
                result.append('.');
            result.append(typeName);
            return findType(result.toString());
        }

        private NameEnvironmentAnswer findType(String className) {
            if (className.equals(targetClassName)) {
                ICompilationUnit compilationUnit = new CompilationUnit(sourceFile, className);
                return new NameEnvironmentAnswer(compilationUnit, null);
            }
            String resourceName = className.replace('.', '/') + ".class";
            try (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, null);
                }
            } 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";
            try (InputStream is = classLoader.getResourceAsStream(resourceName)) {
                return is == null;
            } catch (IOException e) {
                // we are here, since close on is failed. That means it was not null
                return false;
            }
        }

        @Override
        public boolean isPackage(char[][] parentPackageName, char[] packageName) {
            StringBuilder result = new StringBuilder();
            int i = 0;
            if (parentPackageName != null) {
                for (; i < parentPackageName.length; i++) {
                    if (i > 0)
                        result.append('.');
                    result.append(parentPackageName[i]);
                }
            }
            if (Character.isUpperCase(packageName[0])) {
                if (!isPackage(result.toString())) {
                    return false;
                }
            }
            if (i > 0)
                result.append('.');
            result.append(packageName);
            return isPackage(result.toString());
        }

        @Override
        public void cleanup() {
        }
    };
    final IErrorHandlingPolicy policy = DefaultErrorHandlingPolicies.proceedWithAllProblems();
    final Map<String, String> 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);
    }
    // Source JVM
    if (ctxt.getOptions().getCompilerSourceVM() != null) {
        String opt = ctxt.getOptions().getCompilerSourceVM();
        if (opt.equals("1.1")) {
            settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_1);
        } else if (opt.equals("1.2")) {
            settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_2);
        } else if (opt.equals("1.3")) {
            settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_3);
        } else if (opt.equals("1.4")) {
            settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_4);
        } else if (opt.equals("1.5")) {
            settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_5);
        } else if (opt.equals("1.6")) {
            settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_6);
        } else if (opt.equals("1.7")) {
            settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_7);
        } else if (opt.equals("1.8")) {
            settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_8);
        } else if (opt.equals("1.9")) {
            settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_9);
        } else {
            log.warn("Unknown source VM " + opt + " ignored.");
            settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_8);
        }
    } else {
        // Default to 1.8
        settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_8);
    }
    // Target JVM
    if (ctxt.getOptions().getCompilerTargetVM() != null) {
        String opt = ctxt.getOptions().getCompilerTargetVM();
        if (opt.equals("1.1")) {
            settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_1);
        } else if (opt.equals("1.2")) {
            settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_2);
        } else if (opt.equals("1.3")) {
            settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_3);
        } else if (opt.equals("1.4")) {
            settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_4);
        } else if (opt.equals("1.5")) {
            settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_5);
            settings.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_1_5);
        } else if (opt.equals("1.6")) {
            settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_6);
            settings.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_1_6);
        } else if (opt.equals("1.7")) {
            settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_7);
            settings.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_1_7);
        } else if (opt.equals("1.8")) {
            settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_8);
            settings.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_1_8);
        } else if (opt.equals("1.9")) {
            settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_9);
            settings.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_1_9);
        } else {
            log.warn("Unknown target VM " + opt + " ignored.");
            settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_8);
        }
    } else {
        // Default to 1.8
        settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_8);
        settings.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_1_8);
    }
    final IProblemFactory problemFactory = new DefaultProblemFactory(Locale.getDefault());
    final ICompilerRequestor requestor = new ICompilerRequestor() {

        @Override
        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];
                        if (problem.isError()) {
                            String name = new String(problems[i].getOriginatingFileName());
                            try {
                                problemList.add(ErrorDispatcher.createJavacError(name, pageNodes, new StringBuilder(problem.getMessage()), problem.getSourceLineNumber(), ctxt));
                            } catch (JasperException e) {
                                log.error("Error visiting node", e);
                            }
                        }
                    }
                }
                if (problemList.isEmpty()) {
                    ClassFile[] classFiles = result.getClassFiles();
                    for (int i = 0; i < classFiles.length; i++) {
                        ClassFile classFile = classFiles[i];
                        char[][] compoundName = classFile.getCompoundName();
                        StringBuilder classFileName = new StringBuilder(outputDir).append('/');
                        for (int j = 0; j < compoundName.length; j++) {
                            if (j > 0)
                                classFileName.append('/');
                            classFileName.append(compoundName[j]);
                        }
                        byte[] bytes = classFile.getBytes();
                        classFileName.append(".class");
                        try (FileOutputStream fout = new FileOutputStream(classFileName.toString());
                            BufferedOutputStream bos = new BufferedOutputStream(fout)) {
                            bos.write(bytes);
                        }
                    }
                }
            } 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);
    }
    CompilerOptions cOptions = new CompilerOptions(settings);
    cOptions.parseLiteralExpressionsAsConstants = true;
    Compiler compiler = new Compiler(env, policy, cOptions, requestor, problemFactory);
    compiler.compile(compilationUnits);
    if (!ctxt.keepGenerated()) {
        File javaFile = new File(ctxt.getServletJavaFileName());
        javaFile.delete();
    }
    if (!problemList.isEmpty()) {
        JavacErrorDetail[] jeds = problemList.toArray(new JavacErrorDetail[0]);
        errDispatcher.javacError(jeds);
    }
    if (log.isDebugEnabled()) {
        long t2 = System.currentTimeMillis();
        log.debug("Compiled " + ctxt.getServletJavaFileName() + " " + (t2 - t1) + "ms");
    }
    if (ctxt.isPrototypeMode()) {
        return;
    }
    // JSR45 Support
    if (!options.isSmapSuppressed()) {
        SmapUtil.installSmap(smap);
    }
}
Also used : IErrorHandlingPolicy(org.eclipse.jdt.internal.compiler.IErrorHandlingPolicy) NameEnvironmentAnswer(org.eclipse.jdt.internal.compiler.env.NameEnvironmentAnswer) HashMap(java.util.HashMap) ClassFileReader(org.eclipse.jdt.internal.compiler.classfmt.ClassFileReader) ArrayList(java.util.ArrayList) ClassFileReader(org.eclipse.jdt.internal.compiler.classfmt.ClassFileReader) Reader(java.io.Reader) InputStreamReader(java.io.InputStreamReader) BufferedReader(java.io.BufferedReader) JasperException(org.apache.jasper.JasperException) INameEnvironment(org.eclipse.jdt.internal.compiler.env.INameEnvironment) DefaultProblemFactory(org.eclipse.jdt.internal.compiler.problem.DefaultProblemFactory) BufferedOutputStream(java.io.BufferedOutputStream) IProblemFactory(org.eclipse.jdt.internal.compiler.IProblemFactory) ICompilationUnit(org.eclipse.jdt.internal.compiler.env.ICompilationUnit) ICompilationUnit(org.eclipse.jdt.internal.compiler.env.ICompilationUnit) Compiler(org.eclipse.jdt.internal.compiler.Compiler) ClassFile(org.eclipse.jdt.internal.compiler.ClassFile) InputStreamReader(java.io.InputStreamReader) ICompilerRequestor(org.eclipse.jdt.internal.compiler.ICompilerRequestor) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) IOException(java.io.IOException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IProblem(org.eclipse.jdt.core.compiler.IProblem) FileInputStream(java.io.FileInputStream) StringTokenizer(java.util.StringTokenizer) FileOutputStream(java.io.FileOutputStream) BufferedReader(java.io.BufferedReader) CompilerOptions(org.eclipse.jdt.internal.compiler.impl.CompilerOptions) CompilationResult(org.eclipse.jdt.internal.compiler.CompilationResult) ClassFile(org.eclipse.jdt.internal.compiler.ClassFile) File(java.io.File)

Example 5 with IProblemFactory

use of org.eclipse.jdt.internal.compiler.IProblemFactory in project opennms by OpenNMS.

the class CustomJRJdtCompiler method compileUnits.

@Override
protected String compileUnits(final JRCompilationUnit[] units, String classpath, File tempDirFile) {
    final INameEnvironment env = getNameEnvironment(units);
    final IErrorHandlingPolicy policy = DefaultErrorHandlingPolicies.proceedWithAllProblems();
    final CompilerOptions options = getJdtSettings();
    final IProblemFactory problemFactory = new DefaultProblemFactory(Locale.getDefault());
    final CompilerRequestor requestor = getCompilerRequestor(units);
    final Compiler compiler = new Compiler(env, policy, options, requestor, problemFactory);
    do {
        CompilationUnit[] compilationUnits = requestor.processCompilationUnits();
        compiler.compile(compilationUnits);
    } while (requestor.hasMissingMethods());
    requestor.processProblems();
    return requestor.getFormattedProblems();
}
Also used : IErrorHandlingPolicy(org.eclipse.jdt.internal.compiler.IErrorHandlingPolicy) JRCompilationUnit(net.sf.jasperreports.engine.design.JRCompilationUnit) ICompilationUnit(org.eclipse.jdt.internal.compiler.env.ICompilationUnit) JRAbstractJavaCompiler(net.sf.jasperreports.engine.design.JRAbstractJavaCompiler) Compiler(org.eclipse.jdt.internal.compiler.Compiler) ICompilerRequestor(org.eclipse.jdt.internal.compiler.ICompilerRequestor) CompilerOptions(org.eclipse.jdt.internal.compiler.impl.CompilerOptions) INameEnvironment(org.eclipse.jdt.internal.compiler.env.INameEnvironment) DefaultProblemFactory(org.eclipse.jdt.internal.compiler.problem.DefaultProblemFactory) IProblemFactory(org.eclipse.jdt.internal.compiler.IProblemFactory)

Aggregations

IProblemFactory (org.eclipse.jdt.internal.compiler.IProblemFactory)8 DefaultProblemFactory (org.eclipse.jdt.internal.compiler.problem.DefaultProblemFactory)8 Compiler (org.eclipse.jdt.internal.compiler.Compiler)7 ICompilerRequestor (org.eclipse.jdt.internal.compiler.ICompilerRequestor)7 IErrorHandlingPolicy (org.eclipse.jdt.internal.compiler.IErrorHandlingPolicy)7 ICompilationUnit (org.eclipse.jdt.internal.compiler.env.ICompilationUnit)7 INameEnvironment (org.eclipse.jdt.internal.compiler.env.INameEnvironment)7 CompilerOptions (org.eclipse.jdt.internal.compiler.impl.CompilerOptions)7 ByteArrayOutputStream (java.io.ByteArrayOutputStream)5 IOException (java.io.IOException)5 InputStream (java.io.InputStream)5 ArrayList (java.util.ArrayList)5 IProblem (org.eclipse.jdt.core.compiler.IProblem)5 ClassFile (org.eclipse.jdt.internal.compiler.ClassFile)5 CompilationResult (org.eclipse.jdt.internal.compiler.CompilationResult)5 ClassFileReader (org.eclipse.jdt.internal.compiler.classfmt.ClassFileReader)5 NameEnvironmentAnswer (org.eclipse.jdt.internal.compiler.env.NameEnvironmentAnswer)5 HashMap (java.util.HashMap)4 StringTokenizer (java.util.StringTokenizer)4 BufferedOutputStream (java.io.BufferedOutputStream)3