예제 #1
0
  /**
   * @see
   *     org.apache.velocity.runtime.directive.Directive#render(org.apache.velocity.context.InternalContextAdapter,
   *     java.io.Writer, org.apache.velocity.runtime.parser.node.Node)
   */
  @Override
  public boolean render(InternalContextAdapter context, Writer writer, Node node)
      throws IOException, ResourceNotFoundException, ParseErrorException,
          MethodInvocationException {

    //        String path = DirectiveUtil.getRequiredArgument(context,
    // node.jjtGetParent().jjtGetParent(), 0, getName());
    String path = DirectiveUtil.getRequiredArgument(context, node, 0, getName());

    List<String> cs;
    if (context.containsKey(DirectiveEnum.CSS.getCode())) {
      cs = (List<String>) context.get(DirectiveEnum.CSS.getCode());
    } else {
      cs = new ArrayList<String>();
      context.put(DirectiveEnum.CSS.getCode(), cs);
    }
    if (StringUtils.contains(path, ',')) {
      String[] paths = StringUtils.split(path, ',');
      cs.addAll(Arrays.asList(paths));
    } else {
      cs.add(path);
    }

    return true;
  }
예제 #2
0
 /**
  * This creates and places the scope control for this directive into the context (if scope
  * provision is turned on).
  */
 protected void preRender(InternalContextAdapter context) {
   if (isScopeProvided()) {
     String name = getScopeName();
     Object previous = context.get(name);
     context.put(name, makeScope(previous));
   }
 }
예제 #3
0
 public static void velocityInternalContextToBindings(
     InternalContextAdapter context, Binding binding) {
   if (context == null || binding == null) return;
   for (Object k : context.getKeys()) {
     String key = k.toString();
     binding.setVariable(key, context.get(key));
   }
 }
  @Override
  public boolean render(InternalContextAdapter icad, Writer writer, Node node)
      throws IOException, ResourceNotFoundException, ParseErrorException,
          MethodInvocationException {
    Map params = getPareMap(icad, node);
    VelocityContext context = new VelocityContext();
    context.put("imageDomain", imageDomain);
    context.put("cssDomain", cssDomain);
    context.put("jsDomain", jsDomain);
    context.put("sbglpath", sbglpath);
    context.put("strutsaction", strutsaction);
    context.put("webbaseurl", webbaseurl);
    System.out.println("ssssssssssssssssssss");

    try {
      // 获取文件路径
      FrontDirective frontdirective =
          (FrontDirective)
              Class.forName("com.sbgl.actions" + params.get("moduleName") + "Action").newInstance();
      // 处理参数
      Object isPas = params.get("parameters");
      if (isPas != null) {
        setParem(params);
      }
      String tag = params.get("tag").toString();
      if ("HEAD".equals(tag)) {
        frontdirective.head(icad, params, context);
      } else if ("FOOT".equals(tag)) {
        frontdirective.foot(icad, params, context);
      } else if ("WINDOW".equals(tag)) {
        frontdirective.window(icad, params, context);
      }
      String vmpath = params.get("vmpath").toString();
      icad.pushCurrentTemplateName(vmpath);
      Properties properties = new Properties();
      String basePath = ServletActionContext.getServletContext().getRealPath("/");
      properties.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH, basePath);
      // 设置velocity的编码
      properties.setProperty(Velocity.ENCODING_DEFAULT, "utf-8");
      properties.setProperty(Velocity.INPUT_ENCODING, "utf-8");
      properties.setProperty(Velocity.OUTPUT_ENCODING, "utf-8");
      /* 首先创建一个模板引擎的实例,并予以初始化 */
      VelocityEngine engine = new VelocityEngine();
      engine.init(properties);
      /* 接着,获得一个模板 */
      Template template = engine.getTemplate(icad.getCurrentTemplateName());

      /* 现在,把模板和数据合并,输出到StringWriter */
      StringWriter wri = new StringWriter();
      template.merge(context, wri);
      /* 显示结果 */
      writer.write(wri.toString());
    } catch (Exception e) {
      e.printStackTrace();
    }

    return true;
  }
 public boolean render(InternalContextAdapter context, Writer writer)
     throws IOException, MethodInvocationException, ParseErrorException,
         ResourceNotFoundException {
   OverrideNodeWrapper preNode = (OverrideNodeWrapper) context.get(Utils.OVERRIDE_CURRENT_NODE);
   try {
     context.put(Utils.OVERRIDE_CURRENT_NODE, this);
     return current.render(context, writer);
   } finally {
     context.put(Utils.OVERRIDE_CURRENT_NODE, preNode);
   }
 }
예제 #6
0
 private String parseTemplatePath(InternalContextAdapter context, Node node) {
   String path = (String) ((SimpleNode) node.jjtGetChild(0)).value(context);
   String template =
       EventHandlerUtil.includeEvent(
           rsvc, context, path, context.getCurrentTemplateName(), getName());
   return template;
 }
예제 #7
0
 private String getContentTemplate(InternalContextAdapter context) {
   String tpl = (String) context.get(KEY_ASYNC_INCLUDE_CONTENT);
   if (tpl == null || tpl.isEmpty()) {
     tpl = DEFAULT_CONTENT;
   }
   return tpl;
 }
  @Override
  public boolean render(InternalContextAdapter context, Writer writer, Node node)
      throws IOException, ResourceNotFoundException, ParseErrorException,
          MethodInvocationException {

    String name = Utils.getRequiredArgument(context, node, 0, getName());
    OverrideNodeWrapper override =
        (OverrideNodeWrapper) context.get(Utils.getOverrideVariableName(name));
    if (override == null) {
      Node body = node.jjtGetChild(1);
      context.put(Utils.getOverrideVariableName(name), new OverrideNodeWrapper(body));
    } else {
      OverrideNodeWrapper current = new OverrideNodeWrapper(node.jjtGetChild(1));
      Utils.setParentForTop(current, override);
    }
    return true;
  }
예제 #9
0
 @SuppressWarnings("unchecked")
 public static void bindingsToVelocityInternalContext(
     Binding binding, InternalContextAdapter context) {
   if (context == null || binding == null) return;
   for (Object e : binding.getVariables().entrySet()) {
     Entry<String, Object> var = (Entry<String, Object>) e;
     context.put(var.getKey(), var.getValue());
   }
 }
예제 #10
0
  /**
   * This cleans up any scope control for this directive after rendering, assuming the scope control
   * was turned on.
   */
  protected void postRender(InternalContextAdapter context) {
    if (isScopeProvided()) {
      String name = getScopeName();
      Object obj = context.get(name);

      try {
        Scope scope = (Scope) obj;
        if (scope.getParent() != null) {
          context.put(name, scope.getParent());
        } else if (scope.getReplaced() != null) {
          context.put(name, scope.getReplaced());
        } else {
          context.remove(name);
        }
      } catch (ClassCastException cce) {
        // the user can override the scope with a #set,
        // since that means they don't care about a replaced value
        // and obviously aren't too keen on their scope control,
        // and especially since #set is meant to be handled globally,
        // we'll assume they know what they're doing and not worry
        // about replacing anything superseded by this directive's scope
      }
    }
  }
예제 #11
0
  /**
   * Intialize the Runtime macro. At the init time no implementation so we just save the values to
   * use at the render time.
   *
   * @param rs runtime services
   * @param context InternalContextAdapter
   * @param node node containing the macro call
   */
  public void init(RuntimeServices rs, InternalContextAdapter context, Node node) {
    super.init(rs, context, node);
    rsvc = rs;
    this.node = node;

    /**
     * Apply strictRef setting only if this really looks like a macro, so strict mode doesn't balk
     * at things like #E0E0E0 in a template. compare with ")" is a simple #foo() style macro,
     * comparing to "#end" is a block style macro. We use starts with because the token may end with
     * '\n'
     */
    Token t = node.getLastToken();
    if (t.image.startsWith(")") || t.image.startsWith("#end")) {
      strictRef = rsvc.getBoolean(RuntimeConstants.RUNTIME_REFERENCES_STRICT, false);
    }

    // Validate that none of the arguments are plain words, (VELOCITY-614)
    // they should be string literals, references, inline maps, or inline lists
    for (int n = 0; n < node.jjtGetNumChildren(); n++) {
      Node child = node.jjtGetChild(n);
      if (child.getType() == ParserTreeConstants.JJTWORD) {
        badArgsErrorMsg =
            "Invalid arg '"
                + child.getFirstToken().image
                + "' in macro #"
                + macroName
                + " at "
                + Log.formatFileString(child);

        if (strictRef) // If strict, throw now
        {
          /* indicate col/line assuming it starts at 0
           * this will be corrected one call up  */
          throw new TemplateInitException(badArgsErrorMsg, context.getCurrentTemplateName(), 0, 0);
        }
      }
    }
  }
예제 #12
0
  protected String getCacheKey(InternalContextAdapter context, Node node) {
    // 参数个数
    int count = node.jjtGetNumChildren();

    if (count >= 2) {
      // 如果参数有二个,则获取第一个参数当key,当且仅当这个参数是字符串类型
      Object key = node.jjtGetChild(0).value(context);
      if (key instanceof String) {
        return VELOCITY_CACHED_KEY + "|" + key.toString();
      }
    }

    // 宏的使用位置(行号和列号)为key
    String defaultKey =
        new StringBuilder(VELOCITY_CACHED_KEY + "|")
            .append(context.getCurrentTemplateName())
            .append(':')
            .append(node.getLine())
            .append(':')
            .append(node.getColumn())
            .toString();
    return defaultKey;
  }
예제 #13
0
 private boolean isOverrided(InternalContextAdapter context, String name) {
   return context.get(Utils.getOverrideVariableName(name)) != null;
 }
예제 #14
0
  /**
   * This method is used with BlockMacro when we want to render a macro with a body AST.
   *
   * @param context
   * @param writer
   * @param node
   * @param body AST block that was enclosed in the macro body.
   * @return true if the rendering is successful
   * @throws IOException
   * @throws ResourceNotFoundException
   * @throws ParseErrorException
   * @throws MethodInvocationException
   */
  public boolean render(InternalContextAdapter context, Writer writer, Node node, Renderable body)
      throws IOException, ResourceNotFoundException, ParseErrorException,
          MethodInvocationException {
    VelocimacroProxy vmProxy = null;
    String renderingTemplate = context.getCurrentTemplateName();

    /** first look in the source template */
    Object o = rsvc.getVelocimacro(macroName, getTemplateName(), renderingTemplate);

    if (o != null) {
      // getVelocimacro can only return a VelocimacroProxy so we don't need the
      // costly instanceof check
      vmProxy = (VelocimacroProxy) o;
    }

    /** if not found, look in the macro libraries. */
    if (vmProxy == null) {
      List macroLibraries = context.getMacroLibraries();
      if (macroLibraries != null) {
        for (int i = macroLibraries.size() - 1; i >= 0; i--) {
          o = rsvc.getVelocimacro(macroName, (String) macroLibraries.get(i), renderingTemplate);

          // get the first matching macro
          if (o != null) {
            vmProxy = (VelocimacroProxy) o;
            break;
          }
        }
      }
    }

    if (vmProxy != null) {
      try {
        // mainly check the number of arguments
        vmProxy.checkArgs(context, node, body != null);
      } catch (TemplateInitException die) {
        throw new ParseErrorException(
            die.getMessage() + " at " + Log.formatFileString(node), new Info(node));
      }

      if (badArgsErrorMsg != null) {
        throw new TemplateInitException(
            badArgsErrorMsg, context.getCurrentTemplateName(), node.getColumn(), node.getLine());
      }

      try {
        preRender(context);
        return vmProxy.render(context, writer, node, body);
      } catch (StopCommand stop) {
        if (!stop.isFor(this)) {
          throw stop;
        }
        return true;
      } catch (RuntimeException e) {
        /**
         * We catch, the exception here so that we can record in the logs the template and line
         * number of the macro call which generate the exception. This information is especially
         * important for multiple macro call levels. this is also true for the following catch
         * blocks.
         */
        rsvc.getLog()
            .error("Exception in macro #" + macroName + " called at " + Log.formatFileString(node));
        throw e;
      } catch (IOException e) {
        rsvc.getLog()
            .error("Exception in macro #" + macroName + " called at " + Log.formatFileString(node));
        throw e;
      } finally {
        postRender(context);
      }
    } else if (strictRef) {
      throw new VelocityException(
          "Macro '#" + macroName + "' is not defined at " + Log.formatFileString(node));
    }

    /** If we cannot find an implementation write the literal text */
    writer.write(getLiteral());
    return true;
  }
예제 #15
0
  /**
   * computes the result of the division. Currently limited to Integers.
   *
   * @return Integer(value) or null
   */
  public Object value(InternalContextAdapter context) throws MethodInvocationException {
    /*
     *  get the two args
     */

    Object left = jjtGetChild(0).value(context);
    Object right = jjtGetChild(1).value(context);

    /*
     *  if either is null, lets log and bail
     */

    if (left == null || right == null) {
      rsvc.error(
          (left == null ? "Left" : "Right")
              + " side ("
              + jjtGetChild((left == null ? 0 : 1)).literal()
              + ") of division operation has null value."
              + " Operation not possible. "
              + context.getCurrentTemplateName()
              + " [line "
              + getLine()
              + ", column "
              + getColumn()
              + "]");
      return null;
    }

    /*
     *  if not an Integer, not much we can do either
     */

    if (!(left instanceof Integer) || !(right instanceof Integer)) {
      rsvc.error(
          (!(left instanceof Integer) ? "Left" : "Right")
              + " side of division operation is not a valid type. "
              + "Currently only integers (1,2,3...) and Integer type is supported. "
              + context.getCurrentTemplateName()
              + " [line "
              + getLine()
              + ", column "
              + getColumn()
              + "]");

      return null;
    }

    /*
     *  check for divide by 0
     */

    if (((Integer) right).intValue() == 0) {
      rsvc.error(
          "Right side of division operation is zero. Must be non-zero. "
              + context.getCurrentTemplateName()
              + " [line "
              + getLine()
              + ", column "
              + getColumn()
              + "]");

      return null;
    }

    return new Integer(((Integer) left).intValue() / ((Integer) right).intValue());
  }