Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
Copyright (c) 1997-2013, www.tinygroup.org (tinygroup@126.com). Licensed under the GPL, Version 3.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.gnu.org/licenses/gpl.html Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
 
 package org.tinygroup.template.compiler;
 
 
 import java.io.*;
 import java.net.URL;
 import java.util.Map;
 
 
 public class MemorySourceCompiler {
     private String outputDir =  + (.endsWith(.) ? "" : .) + "ttl" + .;
 
 
     public <T> Class<T> loadClass(String engineIdMemorySource sourcethrows TemplateException {
         return loadClass(MemorySourceCompiler.class.getClassLoader(), engineIdsource);
     }
 
     public <T> T loadClass(ClassLoader classLoaderString engineIdMemorySource sourcethrows TemplateException {
         compile(engineIdsource);
         return (T) loadInstance(classLoaderengineIdsource.getQualifiedClassName());
     }
 
     public <T> Class<T> getClass(ClassLoader classLoaderString engineIdString classNamethrows TemplateException {
         try {
             URL[] urls = new URL[1];
             File file = new File(getOutputDir()+engineId+.);
             urls[0] = file.toURI().toURL();
             if (classLoader == null) {
                 return (Class<T>) new URLClassLoader(urls).loadClass(className);
             } else {
                 return (Class<T>) new URLClassLoader(urlsclassLoader).loadClass(className);
             }
         } catch (Exception e) {
             throw new TemplateException(e);
         }
     }
 
     public <T> T loadInstance(String engineIdMemorySource sourcethrows TemplateExceptionInstantiationExceptionIllegalAccessException {
         return (T) loadInstance(MemorySourceCompiler.class.getClassLoader(), engineIdsource);
     }
 
     public <T> T loadInstance(ClassLoader classLoaderString engineIdMemorySource sourcethrows TemplateException {
         return (T) loadInstance(classLoaderengineIdsource.getQualifiedClassName());
     }
 
     public static final String TEMP_DIR = System.getProperty("java.io.tmpdir");
 
     public String getOutputDir() {
         return ;
     }
 
     public void setOutputDir(String outputDir) {
         this. = outputDir;
     }
 
     public <T> T loadInstance(ClassLoader classLoaderString engineIdString classNamethrows TemplateException {
         try {
             return (T) getClass(classLoaderengineIdclassName).newInstance();
         } catch (InstantiationException e) {
             throw new TemplateException(e);
         } catch (IllegalAccessException e) {
             throw new TemplateException(e);
         }
     }
 
     public boolean isModified(ClassName classNameString engineIdString content) {
         String classFileName = className.getClassName().replaceAll("[.]""\\/") + ".class";
         String javaFileName = className.getClassName().replaceAll("[.]""\\/") + ".java";
        File classFile = new File( + engineId + .classFileName);
        File javaFile = new File( + engineId + .javaFileName);
        try {
            if (javaFile.exists()) {
                String contentInDisk = IOUtils.readFromInputStream(new FileInputStream(javaFile), "UTF-8");
                if (contentInDisk.equals(content) && classFile.exists()) {
                    return false;
                }
            }
        } catch (Exception e) {
            //只要出错就认为不存在
        }
        return true;
    }
    class NameEnvironment implements INameEnvironment {
        private final MemorySource[] sources;
        String engineId;
        public NameEnvironment(String engineIdMemorySource[] sources) {
            this. = sources.clone();
            this. = engineId;
        }

        

Parameters:
compoundTypeName {{'j','a','v','a'}, {'l','a','n','g'}}
        public NameEnvironmentAnswer findType(final char[][] compoundTypeName) {
            return findType(join(compoundTypeName));
        }
        public NameEnvironmentAnswer findType(final char[] typeNamefinal char[][] packageName) {
            return findType(join(packageName) + "." + new String(typeName));
        }

        

Parameters:
name like `aaa`,`aaa.BBB`,`java.lang`,`java.lang.String`
        private NameEnvironmentAnswer findType(final String name) {
            // check data dir first
            for (MemorySource source : ) {
                if (name.equals(source.getQualifiedClassName())) {
                    return new NameEnvironmentAnswer(new CompilationUnit(source), null);
                }
            }
            // find by system
            try {
                InputStream input = this.getClass().getClassLoader().getResourceAsStream(name.replace(".""/") + ".class");
                if (input != null) {
                    byte[] bytes = readByteArray(input);
                    if (bytes != null) {
                        ClassFileReader classFileReader = new ClassFileReader(bytesname.toCharArray(), true);
                        return new NameEnvironmentAnswer(classFileReadernull);
                    }
                }
            } catch (ClassFormatException e) {
                // Something very very bad
                throw new RuntimeException(e);
            }
            return null;
        }
        public boolean isPackage(char[][] parentPackageNamechar[] packageName) {
            String name = new String(packageName);
            if (parentPackageName != null) {
                name = join(parentPackageName) + "." + name;
            }
            File target = new File(name.replace('.''/'));
            // only return false if it's a file
            // return true even if it doesn't exist
            return !target.isFile();
        }
        public void cleanup() {
        }
    }
    public void compile(String engineIdCollection<MemorySourcesource) {
        compile(engineIdsource.toArray(new MemorySource[0]));
    }
    public void compile(String engineIdMemorySource source) {
        MemorySource[] sources = new MemorySource[1];
        sources[0] = source;
        compile(engineIdsources);
    }
    public void compile(String engineIdfinal MemorySource[] sources) {
        for (MemorySource source : sources) {
            String javaFileName = source.getQualifiedClassName().replaceAll("[.]""/") + ".java";
            try {
                File file = new File( + engineId + .javaFileName);
                File path = file.getParentFile();
                if (!path.exists()) {
                    path.mkdirs();
                }
                IOUtils.writeToOutputStream(new FileOutputStream(file), source.getContent(), "UTF-8");
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }

        
To find types ...
        INameEnvironment nameEnvironment = new NameEnvironment(engineIdsources);
        
Compilation result
        ICompilerRequestor compilerRequestor = new CompilerRequestor(sources[0],engineId);
        IProblemFactory problemFactory = new DefaultProblemFactory(.);
        IErrorHandlingPolicy policy = DefaultErrorHandlingPolicies.exitOnFirstError();

        
The JDT compiler
        Compiler jdtCompiler = new Compiler(
                nameEnvironmentpolicygetCompilerOptions(), compilerRequestorproblemFactory);
        // Go !
        ICompilationUnit[] units = new ICompilationUnit[sources.length];
        for (int i = 0; i < sources.lengthi++) {
            units[i] = new CompilationUnit(sources[i]);
        }
        jdtCompiler.compile(units);
    }
    public static CharSequence getPrettyError(String[] sourceLinesint lineint inputColumnint startint stopint showLines) {
        int column = inputColumn;
        StringBuilder sb = new StringBuilder(128);
        for (int i = line - showLinesi < linei++) {
            if (i >= 0) {
                String sourceLine = sourceLines[i];
                // 1 个 Tab 变成 4 个空格
                if (i == line - 1) {
                    int originColumn = Math.min(columnsourceLine.length() - 1);
                    for (int j = 0; j < originColumnj++) {
                        char c = sourceLine.charAt(j);
                        if (c == '\t') {
                            column += 3;
                        } else if (c >= '\u2E80' && c <= '\uFE4F') {
                            column++;
                        }
                    }
                }
                sourceLine = sourceLine.replaceAll("\\t""    ");
                sb.append(String.format("%4d: %s%n"i + 1, sourceLine));
            }
        }
        if (start > stop) {
            // <EOF>
            sb.append("      <EOF>\n");
            sb.append("      ^^^^^");
        } else {
            sb.append("      ");
            for (int i = 0; i < column - 1; i++) {
                sb.append(' ');
            }
            for (int i = starti <= stopi++) {
                sb.append('^');
            }
        }
        sb.append('\n');
        return sb;
    }
    private static byte[] readByteArray(InputStream input) {
        BufferedInputStream stream = new BufferedInputStream(input);
        try {
            byte[] buf = new byte[stream.available()];
            stream.read(buf);
            stream.close();
            input.close();
            return buf;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    private void saveClassFile(String engineIdClassFile[] classFiles) {
        if (classFiles == null) {
            return;
        }
        for (int i = 0; i < classFiles.lengthi++) {
            try {
                String fileName = new String(classFiles[i].fileName()) + ".class";
                File javaClassFile = new File( + engineIdfileName);
                if (javaClassFile.exists()) {
                    javaClassFile.delete();
                }
                File pa = javaClassFile.getParentFile();
                if (!pa.exists()) {
                    pa.mkdirs();
                }
                FileOutputStream fout = new FileOutputStream(javaClassFile);
                byte[] bytes = classFiles[i].getBytes();
                fout.write(bytes);
                fout.close();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }
    public static CompilerOptions getCompilerOptions() {
        Map settings = new HashMap();
        settings.put(."UTF-8");
        String javaVersion = .;
        if (System.getProperty("java.version").startsWith("1.6")) {
            javaVersion = .;
        } else if (System.getProperty("java.version").startsWith("1.7")) {
            javaVersion = .;
        }
        settings.put(.javaVersion);
        settings.put(.javaVersion);
        settings.put(.javaVersion);
        return new CompilerOptions(settings);
    }
    private static class CompilationUnit implements ICompilationUnit {
        private final MemorySource source;
        public CompilationUnit(MemorySource source) {
            this. = source;
        }
        public char[] getContents() {
            return .getContent().toCharArray();
        }
        public char[] getMainTypeName() {
            return .getSimpleName().toCharArray();
        }
        public char[][] getPackageName() {
            String[] names = .getQualifiedClassName().split("[.]");
            char[][] result = new char[names.length - 1][];
            for (int i = 0; i < names.length - 1; i++) {
                result[i] = names[i].toCharArray();
            }
            return result;
        }
        public boolean ignoreOptionalProblems() {
            return false;
        }
        public char[] getFileName() {
            return (.getSimpleName() + ".java").toCharArray();
        }
    }
    private static String join(char[][] chars) {
        StringBuilder sb = new StringBuilder();
        for (char[] item : chars) {
            if (sb.length() > 0) {
                sb.append(".");
            }
            sb.append(item);
        }
        return sb.toString();
    }
    class CompilerRequestor implements ICompilerRequestor {
        private final String engineId;
        private final MemorySource source;
        CompilerRequestor(MemorySource sourceString engineId){
            this.=source;
            this.=engineId;
        }
        public void acceptResult(CompilationResult result) {
            if (result.hasErrors()) {
                String sourceCode = .getContent();
                String[] sourceCodeLines = sourceCode.split("(\r\n|\r|\n)", -1);
                StringBuilder sb = new StringBuilder();
                sb.append("Compilation failed.");
                sb.append('\n');
                for (IProblem p : result.getErrors()) {
                    sb.append(p.getMessage()).append('\n');
                    int start = p.getSourceStart();
                    int column = start;
                    for (int i = starti >= 0; i--) {
                        char c = sourceCode.charAt(i);
                        if (c == '\n' || c == '\r') {
                            column = start - i;
                            break;
                        }
                    }
                    sb.append(MemorySourceCompiler.getPrettyError(sourceCodeLinesp.getSourceLineNumber(), columnp.getSourceStart(), p.getSourceEnd(), 3));
                }
                sb.append(result.getErrors().length);
                sb.append(" error(s)\n");
                throw new RuntimeException(sb.toString());
            } else {
                saveClassFile(result.getClassFiles());
            }
        }
    }
New to GrepCode? Check out our FAQ X