Example usage for org.eclipse.jdt.internal.compiler ClassFile getCompoundName

List of usage examples for org.eclipse.jdt.internal.compiler ClassFile getCompoundName

Introduction

In this page you can find the example usage for org.eclipse.jdt.internal.compiler ClassFile getCompoundName.

Prototype

public char[][] getCompoundName() 

Source Link

Document

EXTERNAL API Answer the compound name of the class file.

Usage

From source file:org.apache.sling.scripting.java.jdt.CompilationUnit.java

License:Apache License

/**
 * @see org.eclipse.jdt.internal.compiler.ICompilerRequestor#acceptResult(org.eclipse.jdt.internal.compiler.CompilationResult)
 *//*w  w  w.java2  s .  co  m*/
public void acceptResult(CompilationResult result) {
    try {
        if (result.hasErrors()) {
            IProblem[] errors = result.getErrors();
            for (int i = 0; i < errors.length; i++) {
                IProblem error = errors[i];
                handleError(error.getSourceLineNumber(), -1, error.getMessage());
            }
        } else {
            ClassFile[] classFiles = result.getClassFiles();
            for (int i = 0; i < classFiles.length; i++) {
                ClassFile classFile = classFiles[i];
                char[][] compoundName = classFile.getCompoundName();
                StringBuffer className = new StringBuffer();
                for (int j = 0; j < compoundName.length; j++) {
                    if (j > 0) {
                        className.append(".");
                    }
                    className.append(compoundName[j]);
                }
                byte[] bytes = classFile.getBytes();
                final StringBuffer b = new StringBuffer(this.options.getDestinationPath());
                b.append('/');
                b.append(className.toString().replace('.', '/'));
                b.append(".class");
                OutputStream fout = ioProvider.getOutputStream(b.toString());
                BufferedOutputStream bos = new BufferedOutputStream(fout);
                bos.write(bytes);
                bos.close();
            }
        }
    } catch (IOException exc) {
        exc.printStackTrace();
    }
}

From source file:org.apache.sling.scripting.jsp.jasper.compiler.JDTCompiler.java

License:Apache License

/**
 * Compile the servlet from .java file to .class file
 *//*from   w  w w.  ja  va2s  . co m*/
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();
    String packageName = ctxt.getServletPackageName();
    final String targetClassName = ((packageName.length() != 0) ? (packageName + ".") : "")
            + ctxt.getServletClassName();
    String[] fileNames = new String[] { sourceFile };
    String[] classNames = new String[] { targetClassName };
    final ArrayList problemList = new ArrayList();

    class CompilationUnit implements ICompilationUnit {

        String className;
        String sourceFile;

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

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

        public char[] getContents() {
            char[] result = null;
            InputStream is = null;
            try {
                is = ctxt.getInputStream(sourceFile);
                Reader reader = new BufferedReader(
                        new InputStreamReader(is, ctxt.getOptions().getJavaEncoding()));
                if (reader != null) {
                    char[] chars = new char[8192];
                    StringBuffer buf = new StringBuffer();
                    int count;
                    while ((count = reader.read(chars, 0, chars.length)) > 0) {
                        buf.append(chars, 0, count);
                    }
                    result = new char[buf.length()];
                    buf.getChars(0, result.length, result, 0);
                }
            } catch (IOException e) {
                log.error("Compilation error", e);
            } finally {
                if (is != null) {
                    try {
                        is.close();
                    } catch (IOException exc) {
                        // Ignore
                    }
                }
            }
            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) {

            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 = ctxt.getClassLoader().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 = ctxt.getClassLoader().getResourceAsStream(resourceName);
            return is == null;
        }

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

        public void cleanup() {
        }

    };

    final IErrorHandlingPolicy policy = DefaultErrorHandlingPolicies.proceedWithAllProblems();

    final Map settings = new HashMap();
    settings.put(CompilerOptions.OPTION_LineNumberAttribute, CompilerOptions.GENERATE);
    settings.put(CompilerOptions.OPTION_SourceFileAttribute, CompilerOptions.GENERATE);
    settings.put(CompilerOptions.OPTION_ReportDeprecation, CompilerOptions.IGNORE);
    if (ctxt.getOptions().getJavaEncoding() != null) {
        settings.put(CompilerOptions.OPTION_Encoding, ctxt.getOptions().getJavaEncoding());
    }
    if (ctxt.getOptions().getClassDebugInfo()) {
        settings.put(CompilerOptions.OPTION_LocalVariableAttribute, CompilerOptions.GENERATE);
    }

    // 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 {
            log.warn("Unknown source VM " + opt + " ignored.");
            settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_5);
        }
    } else {
        // Default to 1.5
        settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_5);
    }

    // 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 {
            log.warn("Unknown target VM " + opt + " ignored.");
            settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_5);
        }
    } else {
        // Default to 1.5
        settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_5);
        settings.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_1_5);
    }

    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];
                        if (problem.isError()) {
                            String name = new String(problems[i].getOriginatingFileName());
                            try {
                                problemList.add(ErrorDispatcher.createJavacError(name, pageNodes,
                                        new StringBuffer(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();
                        String className = "";
                        String sep = "";
                        for (int j = 0; j < compoundName.length; j++) {
                            className += sep;
                            className += new String(compoundName[j]);
                            sep = ".";
                        }
                        byte[] bytes = classFile.getBytes();
                        String outFile = outputDir + "/" + className.replace('.', '/') + ".class";
                        OutputStream out = ctxt.getOutputStream(outFile);
                        BufferedOutputStream bos = new BufferedOutputStream(out);
                        bos.write(bytes);
                        bos.close();
                    }
                }
            } catch (IOException exc) {
                log.error("Compilation error", exc);
            }
        }
    };

    ICompilationUnit[] compilationUnits = new ICompilationUnit[classNames.length];
    for (int i = 0; i < compilationUnits.length; i++) {
        String className = classNames[i];
        compilationUnits[i] = new CompilationUnit(fileNames[i], className);
    }
    Compiler compiler = new Compiler(env, policy, settings, requestor, problemFactory, true);
    compiler.compile(compilationUnits);

    if (!ctxt.keepGenerated()) {
        ctxt.delete(ctxt.getServletJavaFileName());
    }

    if (!problemList.isEmpty()) {
        JavacErrorDetail[] jeds = (JavacErrorDetail[]) 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(getCompilationContext(), smap);
    }

}

From source file:org.apache.tuscany.maven.compiler.CompilerRequestor.java

License:Apache License

public void acceptResult(CompilationResult result) {
    boolean hasErrors = false;
    if (result.hasProblems()) {

        // Convert JDT IProblems into plexus CompilerErrors
        for (IProblem problem : result.getProblems()) {
            if (problem.isWarning()) {
                if (showWarnings) {
                    compilerErrors.add(new CompilerError(new String(problem.getOriginatingFileName()), false,
                            problem.getSourceLineNumber(), problem.getSourceStart(),
                            problem.getSourceLineNumber(), problem.getSourceEnd(), problem.getMessage()));
                }//from  w w  w  .j  a  va 2s. c om

            } else if (problem.isError()) {
                hasErrors = true;
                compilerErrors.add(new CompilerError(new String(problem.getOriginatingFileName()), true,
                        problem.getSourceLineNumber(), problem.getSourceStart(), problem.getSourceLineNumber(),
                        problem.getSourceEnd(), problem.getMessage()));

            }
        }
    }

    // Write the class files 
    if (!hasErrors) {
        ClassFile[] classFiles = result.getClassFiles();
        for (ClassFile classFile : classFiles) {

            // Create file and parent directories
            StringBuffer className = new StringBuffer();
            for (char[] name : classFile.getCompoundName()) {
                if (className.length() != 0) {
                    className.append('.');
                }
                className.append(name);
            }
            File file = new File(outputDirectory, className.toString().replace('.', '/') + ".class");
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }

            // Write class file contents
            FileOutputStream fos = null;
            try {
                fos = new FileOutputStream(file);
                fos.write(classFile.getBytes());
            } catch (FileNotFoundException e) {
                throw new IllegalArgumentException(e);
            } catch (IOException e) {
                throw new IllegalArgumentException(e);
            } finally {
                if (fos != null) {
                    try {
                        fos.close();
                    } catch (IOException e) {
                    }
                }
            }
        }
    }
}

From source file:org.auroraide.server.jci.compilers.EclipseJavaCompiler.java

License:Apache License

public org.apache.commons.jci.compilers.CompilationResult compile(final String[] pSourceFiles,
        final ResourceReader pReader, final ResourceStore pStore, final ClassLoader pClassLoader,
        final JavaCompilerSettings pSettings) {

    final Map<?, ?> settingsMap = ((EclipseJavaCompilerSettings) defaultSettings).getMap();

    final Collection<CompilationProblem> problems = new ArrayList<CompilationProblem>();

    final ICompilationUnit[] compilationUnits = new ICompilationUnit[pSourceFiles.length];
    for (int i = 0; i < compilationUnits.length; i++) {
        final String sourceFile = pSourceFiles[i];

        if (pReader.isAvailable(sourceFile)) {
            compilationUnits[i] = new CompilationUnit(pReader, sourceFile);
            log.debug("compiling " + sourceFile);
        } else {//www.  j a v a2s.  co  m
            // log.error("source not found " + sourceFile);

            final CompilationProblem problem = new CompilationProblem() {

                public int getEndColumn() {
                    return 0;
                }

                public int getEndLine() {
                    return 0;
                }

                public String getFileName() {
                    return sourceFile;
                }

                public String getMessage() {
                    return "Source " + sourceFile + " could not be found";
                }

                public int getStartColumn() {
                    return 0;
                }

                public int getStartLine() {
                    return 0;
                }

                public boolean isError() {
                    return true;
                }

                public String toString() {
                    return getMessage();
                }
            };

            if (problemHandler != null) {
                problemHandler.handle(problem);
            }

            problems.add(problem);
        }
    }

    if (problems.size() > 0) {
        final CompilationProblem[] result = new CompilationProblem[problems.size()];
        problems.toArray(result);
        return new org.apache.commons.jci.compilers.CompilationResult(result);
    }

    final IErrorHandlingPolicy policy = DefaultErrorHandlingPolicies.proceedWithAllProblems();
    final IProblemFactory problemFactory = new DefaultProblemFactory(Locale.getDefault());
    final INameEnvironment nameEnvironment = new INameEnvironment() {

        public NameEnvironmentAnswer findType(final char[][] pCompoundTypeName) {
            final StringBuffer result = new StringBuffer();
            for (int i = 0; i < pCompoundTypeName.length; i++) {
                if (i != 0) {
                    result.append('.');
                }
                result.append(pCompoundTypeName[i]);
            }

            //log.debug("finding compoundTypeName=" + result.toString());

            return findType(result.toString());
        }

        public NameEnvironmentAnswer findType(final char[] pTypeName, final char[][] pPackageName) {
            final StringBuffer result = new StringBuffer();
            for (int i = 0; i < pPackageName.length; i++) {
                result.append(pPackageName[i]);
                result.append('.');
            }

            //                log.debug("finding typeName=" + new String(typeName) + " packageName=" + result.toString());

            result.append(pTypeName);
            return findType(result.toString());
        }

        private NameEnvironmentAnswer findType(final String pClazzName) {

            if (isPackage(pClazzName)) {
                return null;
            }

            log.debug("finding " + pClazzName);

            final String resourceName = ConversionUtils.convertClassToResourcePath(pClazzName);

            final byte[] clazzBytes = pStore.read(pClazzName);
            if (clazzBytes != null) {
                log.debug("loading from store " + pClazzName);

                final char[] fileName = pClazzName.toCharArray();
                try {
                    final ClassFileReader classFileReader = new ClassFileReader(clazzBytes, fileName, true);
                    return new NameEnvironmentAnswer(classFileReader, null);
                } catch (final ClassFormatException e) {
                    log.error("wrong class format", e);
                    return null;
                }
            }

            log.debug("not in store " + pClazzName);

            final InputStream is = pClassLoader.getResourceAsStream(resourceName);
            if (is == null) {
                log.debug("class " + pClazzName + " not found");
                return null;
            }

            final byte[] buffer = new byte[8192];
            final ByteArrayOutputStream baos = new ByteArrayOutputStream(buffer.length);
            int count;
            try {
                while ((count = is.read(buffer, 0, buffer.length)) > 0) {
                    baos.write(buffer, 0, count);
                }
                baos.flush();
                final char[] fileName = pClazzName.toCharArray();
                final ClassFileReader classFileReader = new ClassFileReader(baos.toByteArray(), fileName, true);
                return new NameEnvironmentAnswer(classFileReader, null);
            } catch (final IOException e) {
                log.error("could not read class", e);
                return null;
            } catch (final ClassFormatException e) {
                log.error("wrong class format", e);
                return null;
            } finally {
                try {
                    baos.close();
                } catch (final IOException oe) {
                    log.error("could not close output stream", oe);
                }
                try {
                    is.close();
                } catch (final IOException ie) {
                    log.error("could not close input stream", ie);
                }
            }
        }

        private boolean isPackage(final String pClazzName) {

            final InputStream is = pClassLoader
                    .getResourceAsStream(ConversionUtils.convertClassToResourcePath(pClazzName));
            if (is != null) {
                log.debug("found the class for " + pClazzName + "- no package");
                return false;
            }

            // FIXME: this should not be tied to the extension
            final String source = pClazzName.replace('.', '/') + ".java";
            if (pReader.isAvailable(source)) {
                log.debug("found the source " + source + " for " + pClazzName + " - no package ");
                return false;
            }

            return true;
        }

        public boolean isPackage(char[][] parentPackageName, char[] pPackageName) {
            final StringBuffer result = new StringBuffer();
            if (parentPackageName != null) {
                for (int i = 0; i < parentPackageName.length; i++) {
                    if (i != 0) {
                        result.append('.');
                    }
                    result.append(parentPackageName[i]);
                }
            }

            //                log.debug("isPackage parentPackageName=" + result.toString() + " packageName=" + new String(packageName));

            if (parentPackageName != null && parentPackageName.length > 0) {
                result.append('.');
            }
            result.append(pPackageName);
            return isPackage(result.toString());
        }

        public void cleanup() {
            log.debug("cleanup");
        }
    };

    final ICompilerRequestor compilerRequestor = new ICompilerRequestor() {
        public void acceptResult(final CompilationResult pResult) {
            if (pResult.hasProblems()) {
                final IProblem[] iproblems = pResult.getProblems();
                for (int i = 0; i < iproblems.length; i++) {
                    final IProblem iproblem = iproblems[i];
                    final CompilationProblem problem = new EclipseCompilationProblem(iproblem);
                    if (problemHandler != null) {
                        problemHandler.handle(problem);
                    }
                    problems.add(problem);
                }
            }
            if (!pResult.hasErrors()) {
                final ClassFile[] clazzFiles = pResult.getClassFiles();
                for (int i = 0; i < clazzFiles.length; i++) {
                    final ClassFile clazzFile = clazzFiles[i];
                    final char[][] compoundName = clazzFile.getCompoundName();
                    final StringBuffer clazzName = new StringBuffer();
                    for (int j = 0; j < compoundName.length; j++) {
                        if (j != 0) {
                            clazzName.append('.');
                        }
                        clazzName.append(compoundName[j]);
                    }
                    pStore.write(clazzName.toString().replace('.', '/') + ".class", clazzFile.getBytes());
                }
            }
        }
    };

    final Compiler compiler = new Compiler(nameEnvironment, policy, settingsMap, compilerRequestor,
            problemFactory, false);

    compiler.compile(compilationUnits);

    final CompilationProblem[] result = new CompilationProblem[problems.size()];
    problems.toArray(result);
    return new org.apache.commons.jci.compilers.CompilationResult(result);
}

From source file:org.conqat.engine.java.ecj.EcjASTAccessTest.java

License:Apache License

/**
 * When the source path is present on the class path, all referenced classes
 * are compiled by the ECJ. This test checks different aspects of the
 * generated result.//from  w  w  w  .  java  2  s.  c om
 */
public void testWithClasspath() throws IOException {

    String[] classpath = EcjUtils.obtainClasspath(srcFolder.getAbsolutePath());

    CollectingCompilerRequestor requestor = compile(classpath);

    assertEquals(6, requestor.getClassFiles().size());

    HashSet<String> classNames = new HashSet<String>();

    for (ClassFile classFile : requestor.getClassFiles()) {
        classNames.add(EcjUtils.getFQName(classFile.getCompoundName()));
    }

    assertTrue(classNames.contains("MainClass"));
    assertTrue(classNames.contains("ReferencedClass1"));
    assertTrue(classNames.contains("ReferencedClass2"));
    assertTrue(classNames.contains("ReferencedClass2$InnerClass"));
    assertTrue(classNames.contains("ReferencedClass2$InnerClass$InnerClass2ndLevel"));
    assertTrue(classNames.contains("ReferencedClassWithErrors1"));

    // class files
    assertEquals(1, requestor.getClassFiles("MainClass").size());
    assertEquals(1, requestor.getClassFiles("ReferencedClass1").size());
    assertEquals(3, requestor.getClassFiles("ReferencedClass2").size());

    // errors
    assertEquals(0, requestor.getErrors("MainClass").size());
    assertEquals(0, requestor.getErrors("ReferencedClass1").size());
    assertEquals(0, requestor.getErrors("ReferencedClass2").size());
    assertEquals(1, requestor.getErrors("ReferencedClassWithErrors1").size());

    // problems
    assertEquals(1, requestor.getProblems("ReferencedClass1").size());
}

From source file:org.drools.commons.jci.compilers.EclipseJavaCompiler.java

License:Apache License

public org.drools.commons.jci.compilers.CompilationResult compile(final String[] pSourceFiles,
        final ResourceReader pReader, final ResourceStore pStore, final ClassLoader pClassLoader,
        final JavaCompilerSettings pSettings) {

    final Map settingsMap = new EclipseJavaCompilerSettings(pSettings).toNativeSettings();

    final Collection problems = new ArrayList();

    final ICompilationUnit[] compilationUnits = new ICompilationUnit[pSourceFiles.length];
    for (int i = 0; i < compilationUnits.length; i++) {
        final String sourceFile = pSourceFiles[i];

        if (pReader.isAvailable(sourceFile)) {
            compilationUnits[i] = new CompilationUnit(pReader, sourceFile);
        } else {//  www  .  ja  v a 2s  . c  o  m
            // log.error("source not found " + sourceFile);

            final CompilationProblem problem = new CompilationProblem() {

                public int getEndColumn() {
                    return 0;
                }

                public int getEndLine() {
                    return 0;
                }

                public String getFileName() {
                    return sourceFile;
                }

                public String getMessage() {
                    return "Source " + sourceFile + " could not be found";
                }

                public int getStartColumn() {
                    return 0;
                }

                public int getStartLine() {
                    return 0;
                }

                public boolean isError() {
                    return true;
                }

                public String toString() {
                    return getMessage();
                }
            };

            if (problemHandler != null) {
                problemHandler.handle(problem);
            }

            problems.add(problem);
        }
    }

    if (problems.size() > 0) {
        final CompilationProblem[] result = new CompilationProblem[problems.size()];
        problems.toArray(result);
        return new org.drools.commons.jci.compilers.CompilationResult(result);
    }

    final IErrorHandlingPolicy policy = DefaultErrorHandlingPolicies.proceedWithAllProblems();
    final IProblemFactory problemFactory = new DefaultProblemFactory(Locale.getDefault());
    final INameEnvironment nameEnvironment = new INameEnvironment() {

        public NameEnvironmentAnswer findType(final char[][] pCompoundTypeName) {
            final StringBuilder result = new StringBuilder();
            for (int i = 0; i < pCompoundTypeName.length; i++) {
                if (i != 0) {
                    result.append('.');
                }
                result.append(pCompoundTypeName[i]);
            }

            //log.debug("finding compoundTypeName=" + result.toString());

            return findType(result.toString());
        }

        public NameEnvironmentAnswer findType(final char[] pTypeName, final char[][] pPackageName) {
            final StringBuilder result = new StringBuilder();
            for (int i = 0; i < pPackageName.length; i++) {
                result.append(pPackageName[i]);
                result.append('.');
            }

            //                log.debug("finding typeName=" + new String(typeName) + " packageName=" + result.toString());

            result.append(pTypeName);
            return findType(result.toString());
        }

        private NameEnvironmentAnswer findType(final String pClazzName) {

            final String resourceName = ClassUtils.convertClassToResourcePath(pClazzName);

            final byte[] clazzBytes = pStore.read(resourceName);
            if (clazzBytes != null) {
                try {
                    return createNameEnvironmentAnswer(pClazzName, clazzBytes);
                } catch (final ClassFormatException e) {
                    throw new RuntimeException(
                            "ClassFormatException in loading class '" + pClazzName + "' with JCI.");
                }
            }

            InputStream is = null;
            ByteArrayOutputStream baos = null;
            try {
                is = pClassLoader.getResourceAsStream(resourceName);
                if (is == null) {
                    return null;
                }

                final byte[] buffer = new byte[8192];
                baos = new ByteArrayOutputStream(buffer.length);
                int count;
                while ((count = is.read(buffer, 0, buffer.length)) > 0) {
                    baos.write(buffer, 0, count);
                }
                baos.flush();
                return createNameEnvironmentAnswer(pClazzName, baos.toByteArray());
            } catch (final IOException e) {
                throw new RuntimeException("could not read class", e);
            } catch (final ClassFormatException e) {
                throw new RuntimeException("wrong class format", e);
            } finally {
                try {
                    if (baos != null) {
                        baos.close();
                    }
                } catch (final IOException oe) {
                    throw new RuntimeException("could not close output stream", oe);
                }
                try {
                    if (is != null) {
                        is.close();
                    }
                } catch (final IOException ie) {
                    throw new RuntimeException("could not close input stream", ie);
                }
            }
        }

        private NameEnvironmentAnswer createNameEnvironmentAnswer(final String pClazzName,
                final byte[] clazzBytes) throws ClassFormatException {
            final char[] fileName = pClazzName.toCharArray();
            final ClassFileReader classFileReader = new ClassFileReader(clazzBytes, fileName, true);
            return new NameEnvironmentAnswer(classFileReader, null);
        }

        private boolean isSourceAvailable(final String pClazzName, final ResourceReader pReader) {
            // FIXME: this should not be tied to the extension
            final String source = pClazzName.replace('.', '/') + ".java";
            return pReader.isAvailable(source);
        }

        private boolean isPackage(final String pClazzName) {
            InputStream is = null;
            try {
                is = pClassLoader.getResourceAsStream(ClassUtils.convertClassToResourcePath(pClazzName));
                return is == null && !isSourceAvailable(pClazzName, pReader);
            } finally {
                if (is != null) {
                    try {
                        is.close();
                    } catch (IOException e) {
                        throw new RuntimeException("Unable to close stream for resource: " + pClazzName);
                    }
                }
            }
        }

        public boolean isPackage(char[][] parentPackageName, char[] pPackageName) {
            final StringBuilder result = new StringBuilder();
            if (parentPackageName != null) {
                for (int i = 0; i < parentPackageName.length; i++) {
                    if (i != 0) {
                        result.append('.');
                    }
                    result.append(parentPackageName[i]);
                }
            }

            //                log.debug("isPackage parentPackageName=" + result.toString() + " packageName=" + new String(packageName));

            if (parentPackageName != null && parentPackageName.length > 0) {
                result.append('.');
            }
            result.append(pPackageName);
            return isPackage(result.toString());
        }

        public void cleanup() {
        }
    };

    final ICompilerRequestor compilerRequestor = new ICompilerRequestor() {
        public void acceptResult(final CompilationResult pResult) {
            if (pResult.hasProblems()) {
                final IProblem[] iproblems = pResult.getProblems();
                for (int i = 0; i < iproblems.length; i++) {
                    final IProblem iproblem = iproblems[i];
                    final CompilationProblem problem = new EclipseCompilationProblem(iproblem);
                    if (problemHandler != null) {
                        problemHandler.handle(problem);
                    }
                    problems.add(problem);
                }
            }
            if (!pResult.hasErrors()) {
                final ClassFile[] clazzFiles = pResult.getClassFiles();
                for (int i = 0; i < clazzFiles.length; i++) {
                    final ClassFile clazzFile = clazzFiles[i];
                    final char[][] compoundName = clazzFile.getCompoundName();
                    final StringBuilder clazzName = new StringBuilder();
                    for (int j = 0; j < compoundName.length; j++) {
                        if (j != 0) {
                            clazzName.append('.');
                        }
                        clazzName.append(compoundName[j]);
                    }
                    pStore.write(clazzName.toString().replace('.', '/') + ".class", clazzFile.getBytes());
                }
            }
        }
    };

    final Compiler compiler = new Compiler(nameEnvironment, policy, settingsMap, compilerRequestor,
            problemFactory, false);

    compiler.compile(compilationUnits);

    final CompilationProblem[] result = new CompilationProblem[problems.size()];
    problems.toArray(result);
    return new org.drools.commons.jci.compilers.CompilationResult(result);
}

From source file:org.drools.compiler.commons.jci.compilers.EclipseJavaCompiler.java

License:Apache License

public org.drools.compiler.commons.jci.compilers.CompilationResult compile(final String[] pSourceFiles,
        final ResourceReader pReader, final ResourceStore pStore, final ClassLoader pClassLoader,
        final JavaCompilerSettings pSettings) {

    final Map settingsMap = new EclipseJavaCompilerSettings(pSettings).toNativeSettings();

    final Collection problems = new ArrayList();

    final ICompilationUnit[] compilationUnits = new ICompilationUnit[pSourceFiles.length];
    for (int i = 0; i < compilationUnits.length; i++) {
        final String sourceFile = pSourceFiles[i];

        if (pReader.isAvailable(sourceFile)) {
            compilationUnits[i] = new CompilationUnit(pReader, sourceFile);
        } else {/*from   w  w  w.j  a va2  s  .c  o  m*/
            // log.error("source not found " + sourceFile);

            final CompilationProblem problem = new CompilationProblem() {

                public int getEndColumn() {
                    return 0;
                }

                public int getEndLine() {
                    return 0;
                }

                public String getFileName() {
                    return sourceFile;
                }

                public String getMessage() {
                    return "Source " + sourceFile + " could not be found";
                }

                public int getStartColumn() {
                    return 0;
                }

                public int getStartLine() {
                    return 0;
                }

                public boolean isError() {
                    return true;
                }

                public String toString() {
                    return getMessage();
                }
            };

            if (problemHandler != null) {
                problemHandler.handle(problem);
            }

            problems.add(problem);
        }
    }

    if (problems.size() > 0) {
        final CompilationProblem[] result = new CompilationProblem[problems.size()];
        problems.toArray(result);
        return new org.drools.compiler.commons.jci.compilers.CompilationResult(result);
    }

    final IErrorHandlingPolicy policy = DefaultErrorHandlingPolicies.proceedWithAllProblems();
    final IProblemFactory problemFactory = new DefaultProblemFactory(Locale.getDefault());
    final INameEnvironment nameEnvironment = new INameEnvironment() {

        public NameEnvironmentAnswer findType(final char[][] pCompoundTypeName) {
            final StringBuilder result = new StringBuilder();
            for (int i = 0; i < pCompoundTypeName.length; i++) {
                if (i != 0) {
                    result.append('.');
                }
                result.append(pCompoundTypeName[i]);
            }

            //log.debug("finding compoundTypeName=" + result.toString());

            return findType(result.toString());
        }

        public NameEnvironmentAnswer findType(final char[] pTypeName, final char[][] pPackageName) {
            final StringBuilder result = new StringBuilder();
            for (int i = 0; i < pPackageName.length; i++) {
                result.append(pPackageName[i]);
                result.append('.');
            }

            //                log.debug("finding typeName=" + new String(typeName) + " packageName=" + result.toString());

            result.append(pTypeName);
            return findType(result.toString());
        }

        private NameEnvironmentAnswer findType(final String pClazzName) {

            final String resourceName = ClassUtils.convertClassToResourcePath(pClazzName);

            final byte[] clazzBytes = pStore.read(resourceName);
            if (clazzBytes != null) {
                try {
                    return createNameEnvironmentAnswer(pClazzName, clazzBytes);
                } catch (final ClassFormatException e) {
                    throw new RuntimeException(
                            "ClassFormatException in loading class '" + pClazzName + "' with JCI.");
                }
            }

            InputStream is = null;
            ByteArrayOutputStream baos = null;
            try {
                is = pClassLoader.getResourceAsStream(resourceName);
                if (is == null) {
                    return null;
                }

                if (ClassUtils.isWindows() || ClassUtils.isOSX()) {
                    // check it really is a class, this issue is due to windows case sensitivity issues for the class org.kie.Process and path org/droosl/process
                    try {
                        pClassLoader.loadClass(pClazzName);
                    } catch (ClassNotFoundException e) {
                        return null;
                    } catch (NoClassDefFoundError e) {
                        return null;
                    }
                }

                final byte[] buffer = new byte[8192];
                baos = new ByteArrayOutputStream(buffer.length);
                int count;
                while ((count = is.read(buffer, 0, buffer.length)) > 0) {
                    baos.write(buffer, 0, count);
                }
                baos.flush();
                return createNameEnvironmentAnswer(pClazzName, baos.toByteArray());
            } catch (final IOException e) {
                throw new RuntimeException("could not read class", e);
            } catch (final ClassFormatException e) {
                throw new RuntimeException("wrong class format", e);
            } finally {
                try {
                    if (baos != null) {
                        baos.close();
                    }
                } catch (final IOException oe) {
                    throw new RuntimeException("could not close output stream", oe);
                }
                try {
                    if (is != null) {
                        is.close();
                    }
                } catch (final IOException ie) {
                    throw new RuntimeException("could not close input stream", ie);
                }
            }
        }

        private NameEnvironmentAnswer createNameEnvironmentAnswer(final String pClazzName,
                final byte[] clazzBytes) throws ClassFormatException {
            final char[] fileName = pClazzName.toCharArray();
            final ClassFileReader classFileReader = new ClassFileReader(clazzBytes, fileName, true);
            return new NameEnvironmentAnswer(classFileReader, null);
        }

        private boolean isSourceAvailable(final String pClazzName, final ResourceReader pReader) {
            // FIXME: this should not be tied to the extension
            final String javaSource = pClazzName.replace('.', '/') + ".java";
            final String classSource = pClazzName.replace('.', '/') + ".class";
            return pReader.isAvailable(prefix + javaSource) || pReader.isAvailable(prefix + classSource);
        }

        private boolean isPackage(final String pClazzName) {
            InputStream is = null;
            try {
                is = pClassLoader.getResourceAsStream(ClassUtils.convertClassToResourcePath(pClazzName));

                if (is != null) {
                    if (ClassUtils.isWindows() || ClassUtils.isOSX()) {
                        // check it really is a class, this issue is due to windows case sensitivity issues for the class org.kie.Process and path org/droosl/process

                        try {
                            Class cls = pClassLoader.loadClass(pClazzName);
                            if (cls != null) {
                                return true;
                            }
                        } catch (ClassNotFoundException e) {
                            return true;
                        } catch (NoClassDefFoundError e) {
                            return true;
                        }
                    }
                }
                boolean result = is == null && !isSourceAvailable(pClazzName, pReader);
                return result;
            } finally {
                if (is != null) {
                    try {
                        is.close();
                    } catch (IOException e) {
                        throw new RuntimeException("Unable to close stream for resource: " + pClazzName);
                    }
                }
            }
        }

        public boolean isPackage(char[][] parentPackageName, char[] pPackageName) {
            final StringBuilder result = new StringBuilder();
            if (parentPackageName != null) {
                for (int i = 0; i < parentPackageName.length; i++) {
                    if (i != 0) {
                        result.append('.');
                    }
                    result.append(parentPackageName[i]);
                }
            }

            //                log.debug("isPackage parentPackageName=" + result.toString() + " packageName=" + new String(packageName));

            if (parentPackageName != null && parentPackageName.length > 0) {
                result.append('.');
            }
            result.append(pPackageName);
            return isPackage(result.toString());
        }

        public void cleanup() {
        }
    };

    final ICompilerRequestor compilerRequestor = new ICompilerRequestor() {
        public void acceptResult(final CompilationResult pResult) {
            if (pResult.hasProblems()) {
                final IProblem[] iproblems = pResult.getProblems();
                for (int i = 0; i < iproblems.length; i++) {
                    final IProblem iproblem = iproblems[i];
                    final CompilationProblem problem = new EclipseCompilationProblem(iproblem);
                    if (problemHandler != null) {
                        problemHandler.handle(problem);
                    }
                    problems.add(problem);
                }
            }
            if (!pResult.hasErrors()) {
                final ClassFile[] clazzFiles = pResult.getClassFiles();
                for (int i = 0; i < clazzFiles.length; i++) {
                    final ClassFile clazzFile = clazzFiles[i];
                    final char[][] compoundName = clazzFile.getCompoundName();
                    final StringBuilder clazzName = new StringBuilder();
                    for (int j = 0; j < compoundName.length; j++) {
                        if (j != 0) {
                            clazzName.append('.');
                        }
                        clazzName.append(compoundName[j]);
                    }
                    pStore.write(clazzName.toString().replace('.', '/') + ".class", clazzFile.getBytes());
                }
            }
        }
    };

    final Compiler compiler = new Compiler(nameEnvironment, policy, settingsMap, compilerRequestor,
            problemFactory, false);

    compiler.compile(compilationUnits);

    final CompilationProblem[] result = new CompilationProblem[problems.size()];
    problems.toArray(result);
    return new org.drools.compiler.commons.jci.compilers.CompilationResult(result);
}

From source file:org.eclipse.objectteams.otdt.tests.compiler.smap.Requestor.java

License:Open Source License

protected void outputClassFiles(CompilationResult unitResult) {
    if ((unitResult != null) && (!unitResult.hasErrors() || forceOutputGeneration)) {
        ClassFile[] classFiles = unitResult.getClassFiles();
        for (int i = 0, fileCount = classFiles.length; i < fileCount; i++) {
            // retrieve the key and the corresponding classfile
            ClassFile classFile = classFiles[i];
            if (outputPath != null) {
                String relativeName = new String(classFile.fileName()).replace('/', File.separatorChar)
                        + ".class";
                try {
                    org.eclipse.jdt.internal.compiler.util.Util.writeToDisk(true, outputPath, relativeName,
                            classFile);/*from ww w .  j ava 2  s  . c  o  m*/
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (this.lineNumbers != null) {
                ClassFileReader cfr;
                try {
                    cfr = new ClassFileReader(classFile.getBytes(),
                            IClassFileReader.METHOD_INFOS | IClassFileReader.METHOD_BODIES);
                } catch (ClassFormatException e) {
                    throw new AssertionFailedError("Can't read class file: " + e.getMessage());
                }
                for (IMethodInfo method : cfr.getMethodInfos()) {
                    String fullMethodDesignator = String
                            .valueOf(CharOperation.concatWith(classFile.getCompoundName(),
                                    CharOperation.concat(method.getName(), method.getDescriptor()), '.'));
                    int[] expectedNumbers = this.lineNumbers.get(fullMethodDesignator);
                    if (expectedNumbers != null) {
                        this.lineNumbers.remove(fullMethodDesignator);
                        ILineNumberAttribute lineNumberAttribute = method.getCodeAttribute()
                                .getLineNumberAttribute();
                        int[][] table = lineNumberAttribute.getLineNumberTable();
                        Assert.assertEquals("wrong number of line numbers", expectedNumbers.length,
                                table.length);
                        for (int n = 0; n < expectedNumbers.length; n++)
                            Assert.assertEquals("wrong line numeber", expectedNumbers[n], table[n][1]);
                    }
                }
            }
        }
    }
}

From source file:org.eclipse.xtext.xbase.compiler.InMemoryJavaCompiler.java

License:Open Source License

public InMemoryJavaCompiler.Result compile(final JavaSource... sources) {
    final InMemoryJavaCompiler.Result result = new InMemoryJavaCompiler.Result(this.parentClassLoader);
    IErrorHandlingPolicy _proceedWithAllProblems = DefaultErrorHandlingPolicies.proceedWithAllProblems();
    final ICompilerRequestor _function = (CompilationResult it) -> {
        ClassFile[] _classFiles = it.getClassFiles();
        for (final ClassFile cf : _classFiles) {
            final Function1<char[], String> _function_1 = (char[] it_1) -> {
                return String.valueOf(it_1);
            };//from   w ww. j  av  a 2s. c o  m
            result.classMap.put(
                    IterableExtensions.join(ListExtensions.<char[], String>map(
                            ((List<char[]>) Conversions.doWrapArray(cf.getCompoundName())), _function_1), "."),
                    cf.getBytes());
        }
    };
    org.eclipse.jdt.internal.compiler.Compiler compiler = new org.eclipse.jdt.internal.compiler.Compiler(
            this.nameEnv, _proceedWithAllProblems, this.compilerOptions, _function,
            new DefaultProblemFactory() {
                @Override
                public CategorizedProblem createProblem(final char[] originatingFileName, final int problemId,
                        final String[] problemArguments, final int elaborationId,
                        final String[] messageArguments, final int severity, final int startPosition,
                        final int endPosition, final int lineNumber, final int columnNumber) {
                    final CategorizedProblem problem = super.createProblem(originatingFileName, problemId,
                            problemArguments, elaborationId, messageArguments, severity, startPosition,
                            endPosition, lineNumber, columnNumber);
                    result.compilationProblems.add(problem);
                    return problem;
                }

                @Override
                public CategorizedProblem createProblem(final char[] originatingFileName, final int problemId,
                        final String[] problemArguments, final String[] messageArguments, final int severity,
                        final int startPosition, final int endPosition, final int lineNumber,
                        final int columnNumber) {
                    final CategorizedProblem problem = super.createProblem(originatingFileName, problemId,
                            problemArguments, messageArguments, severity, startPosition, endPosition,
                            lineNumber, columnNumber);
                    result.compilationProblems.add(problem);
                    return problem;
                }
            });
    final Function1<JavaSource, CompilationUnit> _function_1 = (JavaSource it) -> {
        char[] _charArray = it.getCode().toCharArray();
        String _fileName = it.getFileName();
        return new CompilationUnit(_charArray, _fileName, null);
    };
    ICompilationUnit[] units = ((ICompilationUnit[]) Conversions.unwrapArray(
            ListExtensions.<JavaSource, CompilationUnit>map(
                    ((List<JavaSource>) Conversions.doWrapArray(sources)), _function_1),
            ICompilationUnit.class));
    compiler.compile(units);
    return result;
}

From source file:org.eclipse.xtext.xbase.testing.InMemoryJavaCompiler.java

License:Open Source License

public InMemoryJavaCompiler.Result compile(final JavaSource... sources) {
    final InMemoryJavaCompiler.Result result = new InMemoryJavaCompiler.Result(this.parentClassLoader);
    IErrorHandlingPolicy _proceedWithAllProblems = DefaultErrorHandlingPolicies.proceedWithAllProblems();
    final ICompilerRequestor _function = (CompilationResult it) -> {
        ClassFile[] _classFiles = it.getClassFiles();
        for (final ClassFile cf : _classFiles) {
            char[][] _compoundName = cf.getCompoundName();
            final Function1<char[], String> _function_1 = (char[] it_1) -> {
                return String.valueOf(it_1);
            };/*from  w  w  w . ja  v a2s .  c o  m*/
            List<String> _map = ListExtensions
                    .<char[], String>map(((List<char[]>) Conversions.doWrapArray(_compoundName)), _function_1);
            String _join = IterableExtensions.join(_map, ".");
            byte[] _bytes = cf.getBytes();
            result.classMap.put(_join, _bytes);
        }
    };
    org.eclipse.jdt.internal.compiler.Compiler compiler = new org.eclipse.jdt.internal.compiler.Compiler(
            this.nameEnv, _proceedWithAllProblems, this.compilerOptions, _function,
            new DefaultProblemFactory() {
                @Override
                public CategorizedProblem createProblem(final char[] originatingFileName, final int problemId,
                        final String[] problemArguments, final int elaborationId,
                        final String[] messageArguments, final int severity, final int startPosition,
                        final int endPosition, final int lineNumber, final int columnNumber) {
                    final CategorizedProblem problem = super.createProblem(originatingFileName, problemId,
                            problemArguments, elaborationId, messageArguments, severity, startPosition,
                            endPosition, lineNumber, columnNumber);
                    result.compilationProblems.add(problem);
                    return problem;
                }

                @Override
                public CategorizedProblem createProblem(final char[] originatingFileName, final int problemId,
                        final String[] problemArguments, final String[] messageArguments, final int severity,
                        final int startPosition, final int endPosition, final int lineNumber,
                        final int columnNumber) {
                    final CategorizedProblem problem = super.createProblem(originatingFileName, problemId,
                            problemArguments, messageArguments, severity, startPosition, endPosition,
                            lineNumber, columnNumber);
                    result.compilationProblems.add(problem);
                    return problem;
                }
            });
    final Function1<JavaSource, CompilationUnit> _function_1 = (JavaSource it) -> {
        String _code = it.getCode();
        char[] _charArray = _code.toCharArray();
        String _fileName = it.getFileName();
        return new CompilationUnit(_charArray, _fileName, null);
    };
    ICompilationUnit[] units = ((ICompilationUnit[]) Conversions.unwrapArray(
            ListExtensions.<JavaSource, CompilationUnit>map(
                    ((List<JavaSource>) Conversions.doWrapArray(sources)), _function_1),
            ICompilationUnit.class));
    compiler.compile(units);
    return result;
}