Compile the class from Java source

@return the bytes that comprise the class file
504019
public synchronized byte[] compile() {
        long start = System.currentTimeMillis();
        try {
            if (null != javaByteCode) {
                return javaByteCode;
            }
            if (null == javaSource) {
                throw new IllegalStateException("Cannot find java source when compiling " + getKey());
            }
            engine().classes().compiler.compile(new String[]{name});
            if (logger.isTraceEnabled()) {
                logger.trace("%sms to compile template: %s", System.currentTimeMillis() - start, getKey());
            }
            return javaByteCode;
        } catch (CompileException.CompilerException e) {
            String cn = e.className;
            TemplateClass tc = S.isEqual(cn, name) ? this : engine().classes().getByClassName(cn);
            if (null == tc) {
                tc = this;
            }
            CompileException ce = new CompileException(engine(), tc, e.javaLineNumber, e.message); // init ce before reset java source to get template line info
            javaSource = null; // force parser to regenerate source. This helps to reload after fixing the tag file compilation failure
            logger.warn("compile failed for %s at line %d",tc.tagName,e.javaLineNumber);
            for (TemplateClass itc:this.includedTemplateClasses) {
               logger.info("\tincluded: %s",itc.tagName);
            }
            throw ce;
        } catch (NullPointerException e) {
            String clazzName = name;
            TemplateClass tc = engine().classes().getByClassName(clazzName);
            if (this != tc) {
                logger.error("tc is not this");
            }
            if (!this.equals(tc)) {
                logger.error("tc not match this");
            }
            logger.error("NPE encountered when compiling template class:" + name);
            throw e;
        } finally {
            if (logger.isTraceEnabled()) {
                logger.trace("%sms to compile template class %s", System.currentTimeMillis() - start, getKey());
            }
        }
    }
1317852
public java.lang.String getJavaClass() {
    java.lang.Object ref = javaClass_;
    if (ref instanceof java.lang.String) {
      return (java.lang.String) ref;
    } else {
      com.google.protobuf.ByteString bs = 
          (com.google.protobuf.ByteString) ref;
      java.lang.String s = bs.toStringUtf8();
      if (bs.isValidUtf8()) {
        javaClass_ = s;
      }
      return s;
    }
  }
59060
public Class parseClass(File file) throws CompilationFailedException, IOException {
        return parseClass(new GroovyCodeSource(file, config.getSourceEncoding()));
    }
553930
@SuppressWarnings("deprecation")
    public void compile(String[] classNames) {

        ICompilationUnit[] compilationUnits = new CompilationUnit[classNames.length];
        for (int i = 0; i < classNames.length; i++) {
            compilationUnits[i] = new CompilationUnit(classNames[i]);
        }
        IErrorHandlingPolicy policy = DefaultErrorHandlingPolicies.exitOnFirstError();
        IProblemFactory problemFactory = new DefaultProblemFactory(Locale.ENGLISH);

        /**
         * To find types ...
         */
        INameEnvironment nameEnvironment = new INameEnvironment() {

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

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

            private NameEnvironmentAnswer findStandType(final String name) throws ClassFormatException {
                if (notFoundTypes.contains(name)) {
                    return null;
                }
                RythmEngine engine = engine();
                byte[] bytes = engine.classLoader().getClassDefinition(name);
                if (bytes != null) {
                    ClassFileReader classFileReader = new ClassFileReader(bytes, name.toCharArray(), true);
                    return new NameEnvironmentAnswer(classFileReader, null);
                }
                if (engine.isProdMode()) {
                    notFoundTypes.add(name);
                } else if (name.matches("^(java\\.|play\\.|com\\.greenlaw110\\.).*")) {
                    notFoundTypes.add(name);
                }
                return null;
            }

            private NameEnvironmentAnswer findType(final String name) {
                try {
                    if (!name.contains(TemplateClass.CN_SUFFIX)) {
                        return findStandType(name);
                    }

                    char[] fileName = name.toCharArray();
                    TemplateClass templateClass = classCache.getByClassName(name);

                    // TemplateClass exists
                    if (templateClass != null) {
                        if (templateClass.javaByteCode != null) {
                            ClassFileReader classFileReader = new ClassFileReader(templateClass.javaByteCode, fileName, true);
                            return new NameEnvironmentAnswer(classFileReader, null);
                        }
                        // Cascade compilation
                        ICompilationUnit compilationUnit = new CompilationUnit(name);
                        return new NameEnvironmentAnswer(compilationUnit, null);
                    }

                    // So it's a standard class
                    return findStandType(name);
                } catch (ClassFormatException e) {
                    // Something very very bad
                    throw new RuntimeException(e);
                }
            }

            @Override
            public boolean isPackage(char[][] parentPackageName, char[] packageName) {
                // Rebuild something usable
                StringBuilder sb = new StringBuilder();
                if (parentPackageName != null) {
                    for (char[] p : parentPackageName) {
                        sb.append(new String(p));
                        sb.append(".");
                    }
                }
                sb.append(new String(packageName));
                String name = sb.toString();
                if (packagesCache.containsKey(name)) {
                    return packagesCache.get(name).booleanValue();
                }
                // Check if thera a .java or .class for this resource
                if (engine().classLoader().getClassDefinition(name) != null) {
                    packagesCache.put(name, false);
                    return false;
                }
                if (engine().classes().getByClassName(name) != null) {
                    packagesCache.put(name, false);
                    return false;
                }
                packagesCache.put(name, true);
                return true;
            }

            public void cleanup() {
            }
        };


        /**
         * Compilation result
         */
        ICompilerRequestor compilerRequestor = new ICompilerRequestor() {

            public void acceptResult(CompilationResult result) {
                // If error
                if (result.hasErrors()) {
                    for (IProblem problem : result.getErrors()) {
                        int line = problem.getSourceLineNumber();
                        String message = problem.getMessage();
                        throw CompileException.compilerException(String.valueOf(result.compilationUnit.getMainTypeName()), line, message);
                    }
                }
                // Something has been compiled
                ClassFile[] clazzFiles = result.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]);
                    }

                    if (logger.isTraceEnabled()) {
                        logger.trace("Compiled %s", getTemplateByClassName(clazzName.toString()));
                    }

                    String cn = clazzName.toString();
                    TemplateClass tc = classCache.getByClassName(cn);
                    if (null == tc) {
                        int pos = cn.indexOf("$");
                        if (-1 != pos) {
                            // inner class
                            TemplateClass root = classCache.getByClassName(cn.substring(0, pos));
                            tc = TemplateClass.createInnerClass(cn, clazzFile.getBytes(), root);
                            tc.delayedEnhance(root);
                            classCache.add(tc);
                        } else {
                            throw new RuntimeException("Cannot find class by name: " + cn);
                        }
                    } else {
                        tc.compiled(clazzFile.getBytes());
                    }
                }
            }
        };

        /**
         * The JDT compiler
         */
        Compiler jdtCompiler = new Compiler(nameEnvironment, policy, settings, compilerRequestor, problemFactory) {

            @Override
            protected void handleInternalException(Throwable e, CompilationUnitDeclaration ud, CompilationResult result) {
            }
        };

        // Go !
        jdtCompiler.compile(compilationUnits);

    }
153042
public void compile() {
        if (compiledSize == 0) {
            ByteBuffer bb = m_container.b();
            compiledSize = bb.position();
            bb.flip();
            m_allocator.track(compiledSize);
        }

        if (log.isTraceEnabled()) {
            StringBuilder sb = new StringBuilder("Compiling buffer:   ");
            ByteBuffer dup = m_container.bDR();
            while (dup.hasRemaining()) {
                sb.append(" ").append(dup.get());
            }
            log.trace(sb.toString());
        }
    }
368313
protected EnumSet<JavaFileObject.Kind> getPackageFileKinds() {
        return EnumSet.of(JavaFileObject.Kind.CLASS, JavaFileObject.Kind.SOURCE);
    }
1345194
public byte[] generate() {
        if (outputDex == null) {
            DexOptions options = new DexOptions();
            options.minSdkVersion = DexFormat.API_NO_EXTENDED_OPCODES;
            outputDex = new DexFile(options);
        }

        for (TypeDeclaration typeDeclaration : types.values()) {
            outputDex.add(typeDeclaration.toClassDefItem());
        }

        try {
            return outputDex.toDex(null, false);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
474687
@Override
    public Byte fromBytes(Class targetClass, byte[] b)
    {
        try
        {
            if (b == null)
            {
                return null;
            }
            // return new Byte(new String(b, Constants.ENCODING));
            return (ByteBuffer.wrap(b).get());
        }
        catch (NumberFormatException e)
        {
            log.warn("Number format exception caught!,returning null!");
            return null;
        }
    }
680800
public static byte[] getBytes(final InputStream sourceInputStream) throws IOException {

    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    byte[] buffer = new byte[BUFFER_SIZE];
    for (int len = 0; (len = sourceInputStream.read(buffer)) != -1;) {
      byteArrayOutputStream.write(buffer, 0, len);
    }
    byte[] arrayOfByte = byteArrayOutputStream.toByteArray();
    return arrayOfByte;
  }
237462
private LookupResult findDecompiled(String name, CompilationUnit compilationUnit, GroovyClassLoader loader) {
        ClassNode node = ClassHelper.make(name);
        if (node.isResolved()) {
            return new LookupResult(null, node);
        }

        DecompiledClassNode asmClass = null;
        String fileName = name.replace('.', '/') + ".class";
        URL resource = loader.getResource(fileName);
        if (resource != null) {
            try {
                asmClass = new DecompiledClassNode(AsmDecompiler.parseClass(resource), new AsmReferenceResolver(this, compilationUnit));
                if (!asmClass.getName().equals(name)) {
                    // this may happen under Windows because getResource is case insensitive under that OS!
                    asmClass = null;
                }
            } catch (IOException e) {
                // fall through and attempt other search strategies
            }
        }

        if (asmClass != null) {
            if (isFromAnotherClassLoader(loader, fileName)) {
                return tryAsScript(name, compilationUnit, asmClass);
            }

            return new LookupResult(null, asmClass);
        }
        return null;
    }
912305
private static byte[] readClass(final InputStream is) throws IOException {
        if (is == null) {
            throw new IOException("Class not found");
        }
        byte[] b = new byte[is.available()];
        int len = 0;
        while (true) {
            int n = is.read(b, len, b.length - len);
            if (n == -1) {
                if (len < b.length) {
                    byte[] c = new byte[len];
                    System.arraycopy(b, 0, c, 0, len);
                    b = c;
                }
                return b;
            }
            len += n;
            if (len == b.length) {
                byte[] c = new byte[b.length + 1000];
                System.arraycopy(b, 0, c, 0, len);
                b = c;
            }
        }
    }
1021253
protected synchronized boolean needsCompile(List<File> sources, File outputDir) throws IOException {
        if (!outputDir.isDirectory())
            return true;

        newestClassFile = null;
        Files.walkFileTree(Paths.get(outputDir.getPath()),
            EnumSet.noneOf(FileVisitOption.class), Integer.MAX_VALUE, new SimpleFileVisitor<Path>() {
                public FileVisitResult visitFile(Path path, BasicFileAttributes attrs) throws IOException {
                    if (path.toString().endsWith(".class")) {
                        File classFile = path.toFile();
                        if (newestClassFile == null || classFile.lastModified() > newestClassFile.lastModified())
                            newestClassFile = classFile;
                    }
                    return FileVisitResult.CONTINUE;
                }
            }
        );
        if (newestClassFile == null)
            return true;  // nothing compiled

        File newestSourceFile = null;
        for (File source : sources) {
            if (newestSourceFile == null || source.lastModified() > newestSourceFile.lastModified())
                newestSourceFile = source;
        }
        for (Asset jar : AssetCache.getJarAssets()) {
            if (newestSourceFile == null || jar.file().lastModified() > newestSourceFile.lastModified())
                newestSourceFile = jar.file();
        }

        boolean needsCompile = newestSourceFile.lastModified() >= newestClassFile.lastModified();
        if (logger.isDebugEnabled()) {
            if (needsCompile)
                logger.debug("Kt needs compile due to " + newestSourceFile + " >= " + newestClassFile);
            else
                logger.debug("Kt no compile due to " + newestSourceFile + " < " + newestClassFile);
        }
        return needsCompile;
    }
1190547
public static boolean compileJavaClass(String sourceCode) {
		try {
			String fileName = getClassName(sourceCode).concat(".java");
			logger.info("Compiling Java Class ({})", fileName);

			File rootDir = JKIOUtil.createTempDirectory();
			String packageDir = getPackageDir(sourceCode);
			File sourceFile ;
			if(packageDir!=null) {
				File file=new File(rootDir,packageDir);
				file.mkdirs();
				sourceFile=new File(file, fileName);
			}else {
				sourceFile=new File(rootDir, fileName);
			}

			JKIOUtil.writeDataToFile(sourceCode, sourceFile);

			// Compile source file.
			JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
			StandardJavaFileManager standardJavaFileManager = compiler.getStandardFileManager(null, null, null);

			standardJavaFileManager.setLocation(StandardLocation.CLASS_PATH, getClassPath());
			standardJavaFileManager.setLocation(StandardLocation.SOURCE_PATH, Arrays.asList(rootDir));

			List<String> options = new ArrayList<String>();

			options.add("-Xlint:unchecked");

			CompilationTask compilationTask = compiler.getTask(null, standardJavaFileManager, null, options, null,
					standardJavaFileManager.getJavaFileObjectsFromFiles(JK.toList(sourceFile)));

			return compilationTask.call();
		} catch (IOException e) {
			JK.throww(e);
			return false;
		}

//		if (compiler.run(System.in, System.out, System.err, sourceFile.getPath()) != 0) {
//			JK.error("Compilation failed, check stack trace");
//		}
	}
158261
public Class defineClass() {
        byte[] bytes;
        try {
            ByteArrayOutputStream bout = new ByteArrayOutputStream();
            writeTo(bout);
            bytes = bout.toByteArray();
        } catch (IOException e) {
            InternalError ie = new InternalError(e.toString());
            ie.initCause(e);
            throw ie;
        }

        if (DEBUG) {
            File file = new File(getClassName().replace('.', '/') + ".class");
            try {
                File tempDir = new File(System.getProperty("java.io.tmpdir"));
                file = new File(tempDir, file.getPath());
            } catch (SecurityException e) {
            }
            try {
                file.getParentFile().mkdirs();
                System.out.println("RuntimeClassFile writing to " + file);
                OutputStream out = new FileOutputStream(file);
                out.write(bytes);
                out.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return mLoader.define(getClassName(), bytes);
    }
1044002
private static RuntimeClassFile createClassFile() {
        // Create a ClassFile with the super class of Object.
        RuntimeClassFile cf = new RuntimeClassFile();

        // Default constructor works only if super class has an accessible
        // no-arg constructor.
        cf.addDefaultConstructor();

        // Add the main method, and construct a CodeBuilder for defining the
        // bytecode.
        TypeDesc[] params = new TypeDesc[] {TypeDesc.STRING.toArrayType()};
        MethodInfo mi = cf.addMethod(Modifiers.PUBLIC_STATIC, "main", null, params);
        CodeBuilder b = new CodeBuilder(mi);

        // Create some types which will be needed later.
        TypeDesc bufferedReader = TypeDesc.forClass("java.io.BufferedReader");
        TypeDesc inputStreamReader = TypeDesc.forClass("java.io.InputStreamReader");
        TypeDesc inputStream = TypeDesc.forClass("java.io.InputStream");
        TypeDesc reader = TypeDesc.forClass("java.io.Reader");
        TypeDesc stringBuffer = TypeDesc.forClass("java.lang.StringBuffer");
        TypeDesc printStream = TypeDesc.forClass("java.io.PrintStream");

        // Declare local variables to be used.
        LocalVariable in = b.createLocalVariable("in", bufferedReader);
        LocalVariable name = b.createLocalVariable("name", TypeDesc.STRING);

        // Create the first line of code, corresponding to 
        // in = new BufferedReader(new InputStreamReader(System.in));
        b.newObject(bufferedReader);
        b.dup();
        b.newObject(inputStreamReader);
        b.dup();
        b.loadStaticField("java.lang.System", "in", inputStream);
        params = new TypeDesc[] {inputStream};
        b.invokeConstructor(inputStreamReader.getRootName(), params);
        params = new TypeDesc[] {reader};
        b.invokeConstructor(bufferedReader.getRootName(), params);
        b.storeLocal(in);

        // Create and locate a label for the start of the "try" block.
        Label tryStart = b.createLabel().setLocation();

        // Create input prompt.
        b.loadStaticField("java.lang.System", "out", printStream);
        b.loadConstant("Please enter your name> ");
        params = new TypeDesc[] {TypeDesc.STRING};
        b.invokeVirtual(printStream, "print", null, params);

        // Read a line from the reader, and store it in the "name" variable.
        b.loadLocal(in);
        b.invokeVirtual(bufferedReader, "readLine", TypeDesc.STRING, null);
        b.storeLocal(name);

        // If no exception is thrown, branch to a label to print the
        // response. The location of the label has not yet been set.
        Label printResponse = b.createLabel();
        b.branch(printResponse);

        // Create and locate a label for the end of the "try" block.
        Label tryEnd = b.createLabel().setLocation();

        // Create the "catch" block.
        b.exceptionHandler(tryStart, tryEnd, "java.io.IOException");
        b.returnVoid();

        // If no exception, then branch to this location to print the response.
        printResponse.setLocation();


        // Create the line of code, corresponding to 
        // System.out.println("Hello, " + name);
        b.loadStaticField("java.lang.System", "out", printStream);
        b.newObject(stringBuffer);
        b.dup();
        b.loadConstant("Hello, ");
        params = new TypeDesc[] {TypeDesc.STRING};
        b.invokeConstructor(stringBuffer, params);
        b.loadLocal(name);
        b.invokeVirtual(stringBuffer, "append", stringBuffer, params);
        b.invokeVirtual(stringBuffer, "toString", TypeDesc.STRING, null);
        params = new TypeDesc[] {TypeDesc.STRING};
        b.invokeVirtual(printStream, "println", null, params);

        // The last instruction reached must be a return or else the class
        // verifier will complain.
        b.returnVoid();

        return cf;
    }
218041
public ClassSource create(final String source) {
    checkNotNull(source);

    String trimmed = source.trim();
    log.trace("Creating class-source from: {}", trimmed);

    // First try and parse the source as a URL
    try {
      return new ClassSourceImpl(new URL(trimmed), null, null);
    }
    catch (MalformedURLException e) {
      log.trace("Not a URL", e);
    }

    // FIXME: This is _slightly_ problematic as if you have a valid file ref
    // FIXME: but the file is missing then it will be treated as inline instead of as a file

    // Then as a File
    try {
      File file = new File(trimmed).getCanonicalFile();
      if (file.exists()) {
        return new ClassSourceImpl(null, file, null);
      }
    }
    catch (IOException e) {
      log.trace("Not a File", e);
    }

    // Else it is an inline
    return new ClassSourceImpl(null, null, new InlineImpl(source));
  }
1170775
public byte[] getBytes() {
		final int len = getVInt();
		final byte[] bytes = new byte[len];
		System.arraycopy(buf, bufPosition, bytes, 0, bytes.length);
		bufPosition += bytes.length;
		return bytes;
	}