Search in sources :

Example 1 with JapidCompilationException

use of cn.bran.japid.compiler.JapidCompilationException in project Japid by branaway.

the class CompilerRequestor method acceptResult.

@Override
public void acceptResult(CompilationResult result) {
    // If error
    if (result.hasErrors()) {
        // bran: sort the problems and report the first one
        CategorizedProblem[] errors = result.getErrors();
        Arrays.sort(errors, new Comparator<CategorizedProblem>() {

            @Override
            public int compare(CategorizedProblem o1, CategorizedProblem o2) {
                return o1.getSourceLineNumber() - o2.getSourceLineNumber();
            }
        });
        for (IProblem problem : errors) {
            String className = new String(problem.getOriginatingFileName()).replace("/", ".");
            className = className.substring(0, className.length() - 5);
            String message = problem.getMessage();
            if (problem.getID() == IProblem.CannotImportPackage) {
                // Non sense !
                message = problem.getArguments()[0] + " cannot be resolved";
            }
            RendererClass rc = this.rendererCompiler.japidClasses.get(className);
            if (rc.getSrcFile() == null)
                throw new RuntimeException("no source file for compiling " + className);
            if (rc.getOriSourceCode() == null)
                throw new RuntimeException("no original source code for compiling " + className);
            JapidTemplate tmpl = new JapidTemplate(rc.getSrcFile().getPath(), rc.getOriSourceCode());
            throw new JapidCompilationException(tmpl, DirUtil.mapJavaLineToSrcLine(rc.getSourceCode(), problem.getSourceLineNumber()), message + " while compiling " + className);
        }
    }
    // 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]);
        }
        byte[] bytes = clazzFile.getBytes();
        JapidFlags.debug("Bytecode generated for " + clazzName);
        // XXX address anonymous inner class issue!! ....$1...
        String cname = clazzName.toString();
        RendererClass rc = this.rendererCompiler.japidClasses.get(cname);
        if (rc == null) {
            if (cname.contains("$")) {
                // inner class
                rc = new RendererClass();
                rc.setClassName(cname);
                this.rendererCompiler.japidClasses.put(cname, rc);
            } else {
                throw new RuntimeException("name not in the classes container: " + cname);
            }
        }
        rc.setBytecode(bytes);
    }
}
Also used : JapidTemplate(cn.bran.japid.template.JapidTemplate) ClassFile(org.eclipse.jdt.internal.compiler.ClassFile) JapidCompilationException(cn.bran.japid.compiler.JapidCompilationException) IProblem(org.eclipse.jdt.core.compiler.IProblem) CategorizedProblem(org.eclipse.jdt.core.compiler.CategorizedProblem)

Example 2 with JapidCompilationException

use of cn.bran.japid.compiler.JapidCompilationException in project Japid by branaway.

the class JapidCommands method reloadChanged.

/**
	 * @param root
	 *            the package root "/"
	 * @return
	 */
public static List<File> reloadChanged(String root) {
    try {
        DirUtil.mkdir(root);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    TranslateTemplateTask t = new TranslateTemplateTask();
    File rootDir = new File(root);
    t.setPackageRoot(rootDir);
    t.setInclude(new File(rootDir, DirUtil.JAPIDVIEWS_ROOT));
    t.clearImports();
    t.importStatic(JapidPlayAdapter.class);
    t.importStatic(Validation.class);
    t.importStatic(JavaExtensions.class);
    t.addAnnotation(NoEnhance.class);
    if (DirUtil.hasLayouts(root))
        t.addImport(DirUtil.JAPIDVIEWS_ROOT + "._layouts.*");
    if (DirUtil.hasJavaTags(root))
        t.addImport(DirUtil.JAPIDVIEWS_ROOT + "._javatags.*");
    if (DirUtil.hasTags(root))
        t.addImport(DirUtil.JAPIDVIEWS_ROOT + "._tags.*");
    t.addImport("models.*");
    t.addImport("controllers.*");
    t.addImport(play.mvc.Scope.class.getName() + ".*");
    t.addImport(play.i18n.Messages.class);
    t.addImport(play.i18n.Lang.class);
    t.addImport(play.mvc.Http.class.getName() + ".*");
    t.addImport(Validation.class.getName());
    t.addImport(play.data.validation.Error.class.getName());
    //		t.addImport("static  japidviews._javatags.JapidWebUtil.*");
    List<String> javatags = DirUtil.scanJavaTags(root);
    for (String f : javatags) {
        t.addImport("static " + f + ".*");
    }
    try {
        t.execute();
    } catch (JapidCompilationException e) {
        //			Play.classes.remove(className);
        throw e;
    }
    List<File> changedFiles = t.getChangedFiles();
    return changedFiles;
}
Also used : Validation(play.data.validation.Validation) TranslateTemplateTask(cn.bran.japid.compiler.TranslateTemplateTask) JapidCompilationException(cn.bran.japid.compiler.JapidCompilationException) JapidCompilationException(cn.bran.japid.compiler.JapidCompilationException) IOException(java.io.IOException) VirtualFile(play.vfs.VirtualFile) File(java.io.File)

Example 3 with JapidCompilationException

use of cn.bran.japid.compiler.JapidCompilationException in project Japid by branaway.

the class JapidPlayRenderer method refreshClasses.

static synchronized void refreshClasses() {
    if (classesInited) {
        if (!timeToRefresh())
            return;
    } else {
        JapidFlags.info("Japid scripts not loaded yet. Initializing them...");
    }
    try {
        // PlayDirUtil.mkdir(templateRoot);
        // find out all removed classes
        List<String> allTemps = isDevMode() ? DirUtil.getAllTemplateFiles(new File(defaultTemplateRoot)) : DirUtil.getAllTemplateFilesJavaFiles(new File(defaultTemplateRoot));
        Set<String> currentClassesOnDir = createNameSet(allTemps);
        Set<String> allNames = new HashSet<String>(currentClassesOnDir);
        Set<String> keySet = japidClasses.keySet();
        // got new templates
        allNames.removeAll(keySet);
        removeRemoved(currentClassesOnDir, keySet);
        for (String c : allNames) {
            RendererClass rc = newRendererClass(c);
            japidClasses.put(c, rc);
        }
        // now all the class set size is up to date
        // now update any Java source code
        List<File> gen = gen(defaultTemplateRoot);
        // this would include both new and updated java
        Set<String> updatedClasses = new HashSet<String>();
        if (gen.size() > 0) {
            for (File f : gen) {
                String className = getClassName(f);
                updatedClasses.add(className);
                RendererClass rendererClass = japidClasses.get(className);
                if (rendererClass == null) {
                    // this should not happen, since
                    throw new RuntimeException("any new class names should have been in the classes container: " + className);
                // rendererClass = newRendererClass(className);
                // classes.put(className, rendererClass);
                }
                JapidRenderer.setSources(rendererClass, f);
                removeInnerClasses(className);
                cleanClassHolder(rendererClass);
            }
        }
        // find all render class without bytecode
        for (Iterator<String> i = japidClasses.keySet().iterator(); i.hasNext(); ) {
            String k = i.next();
            RendererClass rc = japidClasses.get(k);
            if (rc.getSourceCode() == null) {
                if (!rc.getClassName().contains("$")) {
                    String pathname = defaultTemplateRoot + sep + k.replace(".", sep);
                    File f = new File(pathname + ".java");
                    JapidRenderer.setSources(rc, f);
                    cleanClassHolder(rc);
                    updatedClasses.add(k);
                } else {
                    rc.setLastUpdated(0);
                }
            } else {
                if (rc.getBytecode() == null) {
                    cleanClassHolder(rc);
                    updatedClasses.add(k);
                }
            }
        }
        // compile all
        if (updatedClasses.size() > 0) {
            String[] names = new String[updatedClasses.size()];
            int i = 0;
            for (String s : updatedClasses) {
                names[i++] = s;
            }
            long t = System.currentTimeMillis();
            // newly compiled class bytecode bodies are set in the global
            // classes set ready for defining
            compiler.compile(names);
            initJapidClassLoader();
            for (RendererClass rc : japidClasses.values()) {
                try {
                    if (isDevMode())
                        // to enable JIT loading in DEV mode
                        rc.setClz(null);
                    else
                        rc.setClz((Class<JapidTemplateBaseWithoutPlay>) japidClassLoader.loadClass(rc.getClassName()));
                } catch (ClassNotFoundException e) {
                    throw new RuntimeException(e);
                }
            }
            howlong("compile/load time for " + names.length + " classe(s)", t);
            classesInited = true;
        }
    } catch (JapidCompilationException e) {
        if (presentErrorInHtml)
            throw e;
        String tempName = e.getTemplateName();
        if (tempName.startsWith(defaultTemplateRoot)) {
        } else {
            tempName = defaultTemplateRoot + File.separator + tempName;
        }
        VirtualFile vf = VirtualFile.fromRelativePath(tempName);
        CompilationException ce = new CompilationException(vf, "\"" + e.getMessage() + "\"", e.getLineNumber(), 0, 0);
        throw ce;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
Also used : VirtualFile(play.vfs.VirtualFile) CompilationException(play.exceptions.CompilationException) JapidCompilationException(cn.bran.japid.compiler.JapidCompilationException) JapidCompilationException(cn.bran.japid.compiler.JapidCompilationException) JapidTemplateException(cn.bran.japid.exceptions.JapidTemplateException) CompilationException(play.exceptions.CompilationException) JapidCompilationException(cn.bran.japid.compiler.JapidCompilationException) IOException(java.io.IOException) RendererClass(cn.bran.japid.rendererloader.RendererClass) RendererClass(cn.bran.japid.rendererloader.RendererClass) VirtualFile(play.vfs.VirtualFile) File(java.io.File) HashSet(java.util.HashSet)

Example 4 with JapidCompilationException

use of cn.bran.japid.compiler.JapidCompilationException in project Japid by branaway.

the class JapidPlayRenderer method handleException.

public static RenderResult handleException(Throwable e) throws RuntimeException {
    if (!presentErrorInHtml)
        if (e instanceof RuntimeException)
            throw (RuntimeException) e;
        else
            throw new RuntimeException(e);
    // if (Play.mode == Mode.PROD)
    // throw new RuntimeException(e);
    //
    Class<? extends JapidTemplateBaseWithoutPlay> rendererClass = getErrorRendererClass();
    if (e instanceof JapidTemplateException) {
        RenderResult rr = RenderInvokerUtils.invokeRender(rendererClass, (JapidTemplateException) e);
        return (rr);
    }
    if (e instanceof RuntimeException && e.getCause() != null)
        e = e.getCause();
    if (e instanceof JapidCompilationException) {
        JapidCompilationException jce = (JapidCompilationException) e;
        JapidTemplateException te = JapidTemplateException.from(jce);
        RenderResult rr = RenderInvokerUtils.invokeRender(rendererClass, te);
        return (rr);
    }
    e.printStackTrace();
    // find the latest japidviews exception or the controller that caused
    // the exception
    StackTraceElement[] stackTrace = e.getStackTrace();
    for (StackTraceElement ele : stackTrace) {
        String className = ele.getClassName();
        if (className.startsWith("japidviews")) {
            int lineNumber = ele.getLineNumber();
            RendererClass applicationClass = japidClasses.get(className);
            if (applicationClass != null) {
                // let's get the line of problem
                int oriLineNumber = applicationClass.mapJavaLineToJapidScriptLine(lineNumber);
                if (oriLineNumber > 0) {
                    if (rendererClass != null) {
                        String path = applicationClass.getOriSourceCode();
                        JapidTemplateException te = new JapidTemplateException("Japid Error", path + "(" + oriLineNumber + "): " + e.getClass().getName() + ": " + e.getMessage(), oriLineNumber, path, applicationClass.getOriSourceCode());
                        RenderResult rr = RenderInvokerUtils.invokeRender(rendererClass, te);
                        return (rr);
                    }
                }
            }
        } else if (className.startsWith("controllers.")) {
            if (e instanceof RuntimeException)
                throw (RuntimeException) e;
            else
                throw new RuntimeException(e);
        }
    }
    JapidTemplateException te = new JapidTemplateException(e);
    RenderResult rr = RenderInvokerUtils.invokeRender(rendererClass, te);
    return rr;
// if (e instanceof RuntimeException)
// throw (RuntimeException) e;
// else
// throw new RuntimeException(e);
}
Also used : JapidCompilationException(cn.bran.japid.compiler.JapidCompilationException) JapidTemplateException(cn.bran.japid.exceptions.JapidTemplateException) RenderResult(cn.bran.japid.template.RenderResult) RendererClass(cn.bran.japid.rendererloader.RendererClass)

Example 5 with JapidCompilationException

use of cn.bran.japid.compiler.JapidCompilationException in project Japid by branaway.

the class JapidPlugin method beforeDetectingChanges.

@Override
public void beforeDetectingChanges() {
    // have a delay in change detection.
    if (System.currentTimeMillis() - lastTimeChecked.get() < 1000)
        return;
    try {
        List<File> changed = JapidCommands.reloadChanged();
        if (changed.size() > 0) {
            for (File f : changed) {
            // System.out.println("pre-detect changed: " + f.getName());
            }
        }
    } catch (JapidCompilationException e) {
        // turn japid compilation error to Play's template error to get
        // better error reporting
        JapidPlayTemplate jpt = new JapidPlayTemplate();
        jpt.name = e.getTemplateName();
        jpt.source = e.getTemplateSrc();
        // throw new TemplateExecutionException(jpt, e.getLineNumber(),
        // e.getMessage(), e);
        VirtualFile vf = VirtualFile.fromRelativePath("/app/" + e.getTemplateName());
        throw new CompilationException(vf, "\"" + e.getMessage() + "\"", e.getLineNumber(), 0, 0);
    } catch (RuntimeException e) {
        // e.printStackTrace();
        throw e;
    }
    boolean hasRealOrphan = JapidCommands.rmOrphanJava();
    lastTimeChecked.set(System.currentTimeMillis());
    if (hasRealOrphan) {
        // a little messy here. clean the cache in case bad files are delete
        // remove all the existing ApplicationClass will reload everything.
        // ideally we just need to remove the orphan. But the internal cache
        // is not visible. Need API change to do that.
        Play.classes.clear();
        throw new RuntimeException("found orphan template Java artifacts. reload to be safe.");
    }
}
Also used : VirtualFile(play.vfs.VirtualFile) CompilationException(play.exceptions.CompilationException) JapidCompilationException(cn.bran.japid.compiler.JapidCompilationException) JapidCompilationException(cn.bran.japid.compiler.JapidCompilationException) VirtualFile(play.vfs.VirtualFile) File(java.io.File)

Aggregations

JapidCompilationException (cn.bran.japid.compiler.JapidCompilationException)6 JapidTemplateException (cn.bran.japid.exceptions.JapidTemplateException)3 RendererClass (cn.bran.japid.rendererloader.RendererClass)3 File (java.io.File)3 VirtualFile (play.vfs.VirtualFile)3 IOException (java.io.IOException)2 CompilationException (play.exceptions.CompilationException)2 TranslateTemplateTask (cn.bran.japid.compiler.TranslateTemplateTask)1 JapidTemplate (cn.bran.japid.template.JapidTemplate)1 RenderResult (cn.bran.japid.template.RenderResult)1 HashSet (java.util.HashSet)1 CategorizedProblem (org.eclipse.jdt.core.compiler.CategorizedProblem)1 IProblem (org.eclipse.jdt.core.compiler.IProblem)1 ClassFile (org.eclipse.jdt.internal.compiler.ClassFile)1 Validation (play.data.validation.Validation)1