Example usage for org.eclipse.jdt.internal.compiler.env ICompilationUnit ICompilationUnit

List of usage examples for org.eclipse.jdt.internal.compiler.env ICompilationUnit ICompilationUnit

Introduction

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

Prototype

ICompilationUnit

Source Link

Usage

From source file:com.mysema.codegen.ECJEvaluatorFactory.java

License:Apache License

protected void compile(String source, ClassType projectionType, String[] names, Type[] types, String id,
        Map<String, Object> constants) throws IOException {
    // create source
    source = createSource(source, projectionType, names, types, id, constants);

    // compile//from  ww  w . j a  v  a 2  s.co m
    final char[] targetContents = source.toCharArray();
    final String targetName = id;
    final ICompilationUnit[] targetCompilationUnits = new ICompilationUnit[] { new ICompilationUnit() {
        @Override
        public char[] getContents() {
            return targetContents;
        }

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

        @Override
        public char[][] getPackageName() {
            StringTokenizer tok = new StringTokenizer(targetName, ".");
            char[][] result = new char[tok.countTokens() - 1][];
            for (int j = 0; j < result.length; j++) {
                result[j] = tok.nextToken().toCharArray();
            }
            return result;
        }

        @Override
        public char[] getFileName() {
            return CharOperation.concat(targetName.toCharArray(), ".java".toCharArray());
        }

        @Override
        public boolean ignoreOptionalProblems() {
            return true;
        }
    } };

    INameEnvironment env = new INameEnvironment() {

        private String join(char[][] compoundName, char separator) {
            if (compoundName == null) {
                return "";
            } else {
                List<String> parts = Lists.newArrayListWithCapacity(compoundName.length);
                for (char[] part : compoundName) {
                    parts.add(new String(part));
                }
                return Joiner.on(separator).join(parts);
            }
        }

        @Override
        public NameEnvironmentAnswer findType(char[][] compoundTypeName) {
            return findType(join(compoundTypeName, '.'));
        }

        @Override
        public NameEnvironmentAnswer findType(char[] typeName, char[][] packageName) {
            return findType(CharOperation.arrayConcat(packageName, typeName));
        }

        private boolean isClass(String result) {
            if (Strings.isNullOrEmpty(result)) {
                return false;
            }

            // if it's the class we're compiling, then of course it's a class
            if (result.equals(targetName)) {
                return true;
            }
            InputStream is = null;
            try {
                // if this is a class we've already compiled, it's a class
                is = loader.getResourceAsStream(result);
                if (is == null) {
                    // use our normal class loader now...
                    String resourceName = result.replace('.', '/') + ".class";
                    is = parentClassLoader.getResourceAsStream(resourceName);
                    if (is == null && !result.contains(".")) {
                        // we couldn't find the class, and it has no package; is it a core class?
                        is = parentClassLoader.getResourceAsStream("java/lang/" + resourceName);
                    }
                }
                return is != null;
            } finally {
                if (is != null) {
                    try {
                        is.close();
                    } catch (IOException ex) {
                    }
                }
            }
        }

        @Override
        public boolean isPackage(char[][] parentPackageName, char[] packageName) {
            // if the parent is a class, the child can't be a package
            String parent = join(parentPackageName, '.');
            if (isClass(parent))
                return false;

            // if the child is a class, it's not a package
            String qualifiedName = (parent.isEmpty() ? "" : parent + ".") + new String(packageName);
            return !isClass(qualifiedName);
        }

        @Override
        public void cleanup() {
        }

        private NameEnvironmentAnswer findType(String className) {
            String resourceName = className.replace('.', '/') + ".class";
            InputStream is = null;
            try {
                // we're only asking ECJ to compile a single class; we shouldn't need this
                if (className.equals(targetName)) {
                    return new NameEnvironmentAnswer(targetCompilationUnits[0], null);
                }

                is = loader.getResourceAsStream(resourceName);
                if (is == null) {
                    is = parentClassLoader.getResourceAsStream(resourceName);
                }

                if (is != null) {
                    ClassFileReader cfr = new ClassFileReader(ByteStreams.toByteArray(is),
                            className.toCharArray(), true);
                    return new NameEnvironmentAnswer(cfr, null);
                } else {
                    return null;
                }
            } catch (ClassFormatException ex) {
                throw new RuntimeException(ex);
            } catch (IOException e) {
                throw new RuntimeException(e);
            } finally {
                if (is != null) {
                    try {
                        is.close();
                    } catch (IOException e) {
                    }
                }
            }

        }
    };

    ICompilerRequestor requestor = new ICompilerRequestor() {

        @Override
        public void acceptResult(CompilationResult result) {
            if (result.hasErrors()) {
                for (CategorizedProblem problem : result.getProblems()) {
                    if (problem.isError()) {
                        problemList.add(problem.getMessage());
                    }
                }
            } else {
                for (ClassFile clazz : result.getClassFiles()) {
                    try {
                        MemJavaFileObject jfo = (MemJavaFileObject) fileManager.getJavaFileForOutput(
                                StandardLocation.CLASS_OUTPUT, new String(clazz.fileName()),
                                JavaFileObject.Kind.CLASS, null);
                        OutputStream os = jfo.openOutputStream();
                        os.write(clazz.getBytes());
                    } catch (IOException ex) {
                        throw new RuntimeException(ex);
                    }
                }
            }
        }
    };

    problemList.clear();

    IErrorHandlingPolicy policy = DefaultErrorHandlingPolicies.exitAfterAllProblems();
    IProblemFactory problemFactory = new DefaultProblemFactory(Locale.getDefault());

    try {
        //Compiler compiler = new Compiler(env, policy, getCompilerOptions(), requestor, problemFactory, true);
        Compiler compiler = new Compiler(env, policy, compilerOptions, requestor, problemFactory);
        compiler.compile(targetCompilationUnits);
        if (!problemList.isEmpty()) {
            StringBuilder sb = new StringBuilder();
            for (String problem : problemList) {
                sb.append("\t").append(problem).append("\n");
            }
            throw new CodegenException("Compilation of " + id + " failed:\n" + source + "\n" + sb.toString());
        }
    } catch (RuntimeException ex) {
        // if we encountered an IOException, unbox and throw it;
        // if we encountered a ClassFormatException, box it as an IOException and throw it
        // otherwise, it's a legit RuntimeException, 
        //    not one of our checked exceptions boxed as unchecked; just rethrow
        Throwable cause = ex.getCause();
        if (cause != null) {
            if (cause instanceof IOException) {
                throw (IOException) cause;
            } else if (cause instanceof ClassFormatException) {
                throw new IOException(cause);
            }
        }
        throw ex;
    }
}

From source file:org.eclipse.ajdt.core.tests.javaelements.AspectsConvertingParserTest2.java

License:Open Source License

private void assertConvertingParse(String testContentStr) {
    char[] testContent = testContentStr.toCharArray();
    final AspectsConvertingParser convertingParser = new AspectsConvertingParser(testContent);
    convertingParser.content = testContent;
    convertingParser.convert(ConversionOptions.CONSTANT_SIZE);

    ICompilationUnit unit = new ICompilationUnit() {

        public char[] getFileName() {
            return "Test.java".toCharArray();
        }//w w  w.  j a  v a 2  s . c om

        public char[][] getPackageName() {
            return new char[0][];
        }

        public char[] getMainTypeName() {
            return "Test".toCharArray();
        }

        public char[] getContents() {
            return convertingParser.content;
        }

        public boolean ignoreOptionalProblems() {
            return false;
        }
    };
    CompilerOptions options = new CompilerOptions();
    options.sourceLevel = ClassFileConstants.JDK1_5;
    options.targetJDK = ClassFileConstants.JDK1_5;
    Parser parser = new Parser(new ProblemReporter(DefaultErrorHandlingPolicies.proceedWithAllProblems(),
            options, new DefaultProblemFactory()), true);
    CompilationResult result = new CompilationResult(unit, 0, 1, 100);
    CompilationUnitDeclaration decl = parser.parse(unit, result);
    if (result.hasErrors()) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < result.getErrors().length; i++) {
            sb.append("\n\t" + result.getErrors()[i].getMessage());
        }
        sb.append("\n============\nOriginal text:\n" + testContentStr);
        sb.append("\n============\nConverted text:\n" + String.valueOf(convertingParser.content));
        fail("Converted unit has errors:" + sb.toString());
    }
}

From source file:org.eclipse.zest.dot.GraphCreatorViaInternalJdtCompiler.java

License:Open Source License

private URL compileWithInternalJdtCompiler(final File zestFile, final String graphName) {
    /*//from   w  w w.j a va 2  s. c  om
     * TODO we need to set up the environment here. Here, we basically hit
     * the same issue as when running with the Java compiler API: we need
     * the classpath
     */
    INameEnvironment nameEnvironment = new FileSystem(new String[0], new String[0], "UTF-8");
    CompilerOptions compilerOptions = new CompilerOptions();
    compilerOptions.generateClassFiles = true;
    compilerOptions.verbose = true;
    org.eclipse.jdt.internal.compiler.Compiler compiler = new org.eclipse.jdt.internal.compiler.Compiler(
            nameEnvironment, DefaultErrorHandlingPolicies.proceedWithAllProblems(), compilerOptions,
            new ICompilerRequestor() {
                public void acceptResult(final CompilationResult result) {
                    CategorizedProblem[] errors = result.getErrors();
                    for (CategorizedProblem categorizedProblem : errors) {
                        System.out.println(String.format("%s: '%s' (%s, line %s)",
                                categorizedProblem.getMarkerType(), categorizedProblem.getMessage(),
                                new String(categorizedProblem.getOriginatingFileName()),
                                categorizedProblem.getSourceLineNumber()));
                    }

                }
            }, ProblemFactory.getProblemFactory(Locale.getDefault()));

    compiler.compile(new ICompilationUnit[] { new ICompilationUnit() {
        public char[] getFileName() {
            return zestFile.getAbsolutePath().toCharArray();
        }

        public char[][] getPackageName() {
            return null;
        }

        public char[] getMainTypeName() {
            return graphName.toCharArray();
        }

        public char[] getContents() {
            return read(zestFile).toCharArray();
        }
    } });
    try {
        URL url = zestFile.getParentFile().toURI().toURL();
        return url;
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }
    return null;
}