private boolean renderTemplate(
      Object target, GroovyObject controller, GrailsWebRequest webRequest, Map argMap, Writer out) {
    boolean renderView;
    String templateName = argMap.get(ARGUMENT_TEMPLATE).toString();
    String contextPath = getContextPath(webRequest, argMap);

    String var = (String) argMap.get(ARGUMENT_VAR);
    // get the template uri
    String templateUri = GroovyPageUtils.getTemplateURI(controller, templateName);

    // retrieve gsp engine
    GroovyPagesTemplateEngine engine =
        (GroovyPagesTemplateEngine)
            webRequest.getApplicationContext().getBean(GroovyPagesTemplateEngine.BEAN_ID);
    try {
      Resource r = engine.getResourceForUri(contextPath + templateUri);
      if (!r.exists()) {
        r = engine.getResourceForUri(contextPath + "/grails-app/views/" + templateUri);
      }

      Template t = engine.createTemplate(r); // templateUri);

      if (t == null) {
        throw new ControllerExecutionException(
            "Unable to load template for uri [" + templateUri + "]. Template not found.");
      }
      Map binding = new HashMap();

      if (argMap.containsKey(ARGUMENT_BEAN)) {
        Object bean = argMap.get(ARGUMENT_BEAN);
        if (argMap.containsKey(ARGUMENT_MODEL)) {
          Object modelObject = argMap.get(ARGUMENT_MODEL);
          if (modelObject instanceof Map) binding.putAll((Map) modelObject);
        }
        renderTemplateForBean(t, binding, bean, var, out);
      } else if (argMap.containsKey(ARGUMENT_COLLECTION)) {
        Object colObject = argMap.get(ARGUMENT_COLLECTION);
        if (argMap.containsKey(ARGUMENT_MODEL)) {
          Object modelObject = argMap.get(ARGUMENT_MODEL);
          if (modelObject instanceof Map) binding.putAll((Map) modelObject);
        }
        renderTemplateForCollection(t, binding, colObject, var, out);
      } else if (argMap.containsKey(ARGUMENT_MODEL)) {
        Object modelObject = argMap.get(ARGUMENT_MODEL);
        renderTemplateForModel(t, modelObject, target, out);
      } else {
        Writable w = t.make(new BeanMap(target));
        w.writeTo(out);
      }
      renderView = false;
    } catch (GroovyRuntimeException gre) {
      throw new ControllerExecutionException(
          "Error rendering template [" + templateName + "]: " + gre.getMessage(), gre);
    } catch (IOException ioex) {
      throw new ControllerExecutionException(
          "I/O error executing render method for arguments [" + argMap + "]: " + ioex.getMessage(),
          ioex);
    }
    return renderView;
  }
Example #2
0
 public void testInvokerException() throws Throwable {
   try {
     throw new GroovyRuntimeException("message", new NullPointerException());
   } catch (GroovyRuntimeException e) {
     // worked
     assertEquals("message", e.getMessage());
     assertTrue(e.getCause() instanceof NullPointerException);
   }
 }
 private Object autoInstantiateDomainInstance(Class<?> type) {
   Object created = null;
   try {
     MetaClass mc = GroovySystem.getMetaClassRegistry().getMetaClass(type);
     if (mc != null) {
       created = mc.invokeStaticMethod(type, CreateDynamicMethod.METHOD_NAME, new Object[0]);
     }
   } catch (MissingMethodException mme) {
     LOG.warn("Unable to auto-create type, 'create' method not found");
   } catch (GroovyRuntimeException gre) {
     LOG.warn("Unable to auto-create type, Groovy Runtime error: " + gre.getMessage(), gre);
   }
   return created;
 }
  // GroovyClassVisitor interface
  // -------------------------------------------------------------------------
  public void visitClass(ClassNode classNode) {
    try {
      this.classNode = classNode;
      this.internalClassName = BytecodeHelper.getClassInternalName(classNode);

      // System.out.println("Generating class: " + classNode.getName());

      this.internalBaseClassName = BytecodeHelper.getClassInternalName(classNode.getSuperClass());

      cv.visit(
          Opcodes.V1_3,
          classNode.getModifiers(),
          internalClassName,
          (String) null,
          internalBaseClassName,
          BytecodeHelper.getClassInternalNames(classNode.getInterfaces()));

      classNode.visitContents(this);

      for (Iterator iter = innerClasses.iterator(); iter.hasNext(); ) {
        ClassNode innerClass = (ClassNode) iter.next();
        ClassNode innerClassType = innerClass;
        String innerClassInternalName = BytecodeHelper.getClassInternalName(innerClassType);
        String outerClassName = internalClassName; // default for inner classes
        MethodNode enclosingMethod = innerClass.getEnclosingMethod();
        if (enclosingMethod != null) {
          // local inner classes do not specify the outer class name
          outerClassName = null;
        }
        cv.visitInnerClass(
            innerClassInternalName,
            outerClassName,
            innerClassType.getName(),
            innerClass.getModifiers());
      }
      cv.visitEnd();
    } catch (GroovyRuntimeException e) {
      e.setModule(classNode.getModule());
      throw e;
    }
  }
        public void call(SourceUnit source, GeneratorContext context, ClassNode classNode)
            throws CompilationFailedException {

          optimizer.visitClass(
              classNode, source); // GROOVY-4272: repositioned it here from staticImport

          if (!classNode.isSynthetic()) {
            GenericsVisitor genericsVisitor = new GenericsVisitor(source);
            genericsVisitor.visitClass(classNode);
          }
          //
          // Run the Verifier on the outer class
          //
          try {
            verifier.visitClass(classNode);
          } catch (GroovyRuntimeException rpe) {
            ASTNode node = rpe.getNode();
            getErrorCollector()
                .addError(
                    new SyntaxException(
                        rpe.getMessage(),
                        node.getLineNumber(),
                        node.getColumnNumber(),
                        node.getLastLineNumber(),
                        node.getLastColumnNumber()),
                    source);
          }

          LabelVerifier lv = new LabelVerifier(source);
          lv.visitClass(classNode);

          ClassCompletionVerifier completionVerifier = new ClassCompletionVerifier(source);
          completionVerifier.visitClass(classNode);

          ExtendedVerifier xverifier = new ExtendedVerifier(source);
          xverifier.visitClass(classNode);

          // because the class may be generated even if a error was found
          // and that class may have an invalid format we fail here if needed
          getErrorCollector().failIfErrors();

          //
          // Prep the generator machinery
          //
          ClassVisitor visitor = createClassVisitor();

          String sourceName =
              (source == null ? classNode.getModule().getDescription() : source.getName());
          // only show the file name and its extension like javac does in its stacktraces rather
          // than the full path
          // also takes care of both \ and / depending on the host compiling environment
          if (sourceName != null)
            sourceName =
                sourceName.substring(
                    Math.max(sourceName.lastIndexOf('\\'), sourceName.lastIndexOf('/')) + 1);
          AsmClassGenerator generator = new AsmClassGenerator(source, context, visitor, sourceName);

          //
          // Run the generation and create the class (if required)
          //
          // GRECLIPSE: if there are errors, don't generate code.
          // code gen can fail unexpectedly if there was an earlier error.
          if (!source.getErrorCollector().hasErrors()) {
            // end
            generator.visitClass(classNode);

            byte[] bytes = ((ClassWriter) visitor).toByteArray();
            /// GRECLIPSE: start: added classNode, sourceUnit
            /*old{
            generatedClasses.add(new GroovyClass(classNode.getName(), bytes));
            }*/
            // newcode
            generatedClasses.add(new GroovyClass(classNode.getName(), bytes, classNode, source));
            // end

            //
            // Handle any callback that's been set
            //
            if (CompilationUnit.this.classgenCallback != null) {
              classgenCallback.call(visitor, classNode);
            }

            //
            // Recurse for inner classes
            //
            LinkedList innerClasses = generator.getInnerClasses();
            while (!innerClasses.isEmpty()) {
              classgen.call(source, context, (ClassNode) innerClasses.removeFirst());
            }
            // GRECLIPSE: if there are errors, don't generate code
          }
          // end
        }