org.apache.velocity.exception.MethodInvocationException Java Examples

The following examples show how to use org.apache.velocity.exception.MethodInvocationException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: MarkdownRenderer.java    From bazel with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a markdown rendering of aspect documentation for the given aspect information object
 * with the given aspect name.
 */
public String render(String aspectName, AspectInfo aspectInfo) throws IOException {
  VelocityContext context = new VelocityContext();
  context.put("util", new MarkdownUtil());
  context.put("aspectName", aspectName);
  context.put("aspectInfo", aspectInfo);

  StringWriter stringWriter = new StringWriter();
  Reader reader = readerFromPath(aspectTemplateFilename);
  try {
    velocityEngine.evaluate(context, stringWriter, aspectTemplateFilename, reader);
  } catch (ResourceNotFoundException | ParseErrorException | MethodInvocationException e) {
    throw new IOException(e);
  }
  return stringWriter.toString();
}
 
Example #2
Source File: VelocityView.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * Merge the template with the context.
 * Can be overridden to customize the behavior.
 * @param template the template to merge
 * @param context the Velocity context to use for rendering
 * @param response servlet response (use this to get the OutputStream or Writer)
 * @throws Exception if thrown by Velocity
 * @see org.apache.velocity.Template#merge
 */
protected void mergeTemplate(
		Template template, Context context, HttpServletResponse response) throws Exception {

	try {
		template.merge(context, response.getWriter());
	}
	catch (MethodInvocationException ex) {
		Throwable cause = ex.getWrappedThrowable();
		throw new NestedServletException(
				"Method invocation failed during rendering of Velocity view with name '" +
				getBeanName() + "': " + ex.getMessage() + "; reference [" + ex.getReferenceName() +
				"], method '" + ex.getMethodName() + "'",
				cause==null ? ex : cause);
	}
}
 
Example #3
Source File: S3Storage.java    From streamx with Apache License 2.0 6 votes vote down vote up
@Override
public WAL wal(String topicsDir, TopicPartition topicPart) {
  try {
    Class<? extends WAL> walClass = (Class<? extends WAL>) Class
        .forName(config.getString(S3SinkConnectorConfig.WAL_CLASS_CONFIG));
    if (walClass.equals(DummyWAL.class)) {
      return new DummyWAL();
    }
    else {
      Constructor<? extends WAL> ctor = walClass.getConstructor(String.class, TopicPartition.class, Storage.class, HdfsSinkConnectorConfig.class);
      return ctor.newInstance(topicsDir, topicPart, this, config);
    }
  } catch (ClassNotFoundException | NoSuchMethodException | InvocationTargetException | MethodInvocationException | InstantiationException | IllegalAccessException e) {
    throw new ConnectException(e);
  }
}
 
Example #4
Source File: ASTOrNode.java    From velocity-engine with Apache License 2.0 6 votes vote down vote up
/**
 *  the logical or :
 *    <pre>
 *      left || null -&gt; left
 *      null || right -&gt; right
 *      null || null -&gt; false
 *      left || right -&gt;  left || right
 *    </pre>
 * @param context
 * @return The evaluation result.
 * @throws MethodInvocationException
 */
public boolean evaluate( InternalContextAdapter context)
    throws MethodInvocationException
{
    Node left = jjtGetChild(0);
    Node right = jjtGetChild(1);

    /*
     *  if the left is not null and true, then true
     */

    if (left != null && left.evaluate( context ) )
        return true;

    /*
     *  same for right
     */

    return right != null && right.evaluate(context);
}
 
Example #5
Source File: VelocityView.java    From scoold with Apache License 2.0 6 votes vote down vote up
/**
 * Merge the template with the context. Can be overridden to customize the behavior.
 *
 * @param template the template to merge
 * @param context the Velocity context to use for rendering
 * @param response servlet response (use this to get the OutputStream or Writer)
 * @throws Exception if thrown by Velocity
 * @see org.apache.velocity.Template#merge
 */
protected void mergeTemplate(
		Template template, Context context, HttpServletResponse response) throws Exception {

	try {
		response.setCharacterEncoding(Config.DEFAULT_ENCODING);
		template.merge(context, response.getWriter());
	} catch (MethodInvocationException ex) {
		Throwable cause = ex.getCause();
		throw new NestedServletException(
				"Method invocation failed during rendering of Velocity view with name '"
				+ getBeanName() + "': " + ex.getMessage() + "; reference [" + ex.getReferenceName()
				+ "], method '" + ex.getMethodName() + "'",
				cause == null ? ex : cause);
	}
}
 
Example #6
Source File: AgnVelocityUberspector.java    From openemm with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Checks method call or property accesses (which are performed by calling getter or setter).
 * 
 * @param method called method
 * @param args arguments
 * @param info information on template
 * 
 * @throws VelocityCheckerException 
 */
private void checkMethodAccess( Method method, Object[] args, Info info) {
	List<ParameterAnnotationDescriptor> list = annotationIntrospector.getParameterAnnotation( method, VelocityCheck.class);
	
	if( logger.isInfoEnabled()) {
		logger.info( "Check access for method " + method.getName());
		for( ParameterAnnotationDescriptor pad : list) {
			logger.info( "Annotation for parameter " + pad.getParameterIndex() + " is " + pad.getAnnotation().annotationType().getName());
		}
		
	}

	try {
		performChecksOnParameters( method, args, list);
	} catch( VelocityCheckerException e) {
		logger.fatal( "Runtime check of Velocity script failed! (" + info + ")", e);
		
		if( isAbortScriptsEnabled()) {
			logger.info( "Aborting script by exception");
			throw new MethodInvocationException( "Aborting Velocity script", e, method.getName(), info.getTemplateName(), info.getLine(), info.getColumn());
		}
	} 
}
 
Example #7
Source File: VelocityView.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Merge the template with the context.
 * Can be overridden to customize the behavior.
 * @param template the template to merge
 * @param context the Velocity context to use for rendering
 * @param response servlet response (use this to get the OutputStream or Writer)
 * @throws Exception if thrown by Velocity
 * @see org.apache.velocity.Template#merge
 */
protected void mergeTemplate(
		Template template, Context context, HttpServletResponse response) throws Exception {

	try {
		template.merge(context, response.getWriter());
	}
	catch (MethodInvocationException ex) {
		Throwable cause = ex.getWrappedThrowable();
		throw new NestedServletException(
				"Method invocation failed during rendering of Velocity view with name '" +
				getBeanName() + "': " + ex.getMessage() + "; reference [" + ex.getReferenceName() +
				"], method '" + ex.getMethodName() + "'",
				cause==null ? ex : cause);
	}
}
 
Example #8
Source File: Split.java    From CodeGen with MIT License 6 votes vote down vote up
@Override
public boolean render(InternalContextAdapter context, Writer writer, Node node) throws IOException, ResourceNotFoundException, ParseErrorException, MethodInvocationException {
    String value = (String) node.jjtGetChild(0).value(context);
    String character = (String) node.jjtGetChild(1).value(context);
    int len = value.length();
    StringBuilder sb = new StringBuilder(len);
    sb.append(value.charAt(0));
    for (int i = 1; i < len; i++) {
        char c = value.charAt(i);
        if (Character.isUpperCase(c)) {
            sb.append(character).append(Character.toLowerCase(c));
        } else {
            sb.append(c);
        }
    }
    writer.write(sb.toString());
    return true;
}
 
Example #9
Source File: VelocityResponseWriterTest.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
@Test
@Ignore("SOLR-14025: Velocity's SecureUberspector addresses this")
public void testTemplateSandbox() throws Exception {
  assumeTrue("This test only works with security manager", System.getSecurityManager() != null);
  VelocityResponseWriter vrw = new VelocityResponseWriter();
  NamedList<String> nl = new NamedList<>();
  nl.add("template.base.dir", getFile("velocity").getAbsolutePath());
  vrw.init(nl);
  SolrQueryRequest req = req(VelocityResponseWriter.TEMPLATE,"outside_the_box");
  SolrQueryResponse rsp = new SolrQueryResponse();
  StringWriter buf = new StringWriter();
  try {
    vrw.write(buf, req, rsp);
    fail("template broke outside the box, retrieved: " + buf);
  } catch (MethodInvocationException e) {
    assertNotNull(e.getCause());
    assertEquals(AccessControlException.class, e.getCause().getClass());
    // expected failure, can't get outside the box
  }
}
 
Example #10
Source File: VelocityResponseWriterTest.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
@Test
@Ignore("SOLR-14025: Velocity's SecureUberspector addresses this")
public void testSandboxIntersection() throws Exception {
  assumeTrue("This test only works with security manager", System.getSecurityManager() != null);
  VelocityResponseWriter vrw = new VelocityResponseWriter();
  NamedList<String> nl = new NamedList<>();
  nl.add("template.base.dir", getFile("velocity").getAbsolutePath());
  vrw.init(nl);
  SolrQueryRequest req = req(VelocityResponseWriter.TEMPLATE,"sandbox_intersection");
  SolrQueryResponse rsp = new SolrQueryResponse();
  StringWriter buf = new StringWriter();
  try {
    vrw.write(buf, req, rsp);
    fail("template broke outside the box, retrieved: " + buf);
  } catch (MethodInvocationException e) {
    assertNotNull(e.getCause());
    assertEquals(AccessControlException.class, e.getCause().getClass());
    // expected failure, can't get outside the box
  }
}
 
Example #11
Source File: VelocityNonStrictHelperTest.java    From herd with Apache License 2.0 6 votes vote down vote up
@Test
public void testEvaluateStrict()
{
    String template = "${baz}";
    Map<String, Object> variables = new HashMap<>();
    variables.put("foo", "bar");
    String logTag = "test";

    try
    {
        velocityNonStrictHelper.evaluate(template, variables, logTag);
        fail();
    }
    catch (MethodInvocationException methodInvocationException)
    {
        Assert.assertEquals("Exception message not equal.", "Variable $baz has not been set at test[line 1, column 1]",
            methodInvocationException.getMessage());
    }
}
 
Example #12
Source File: WrappedExceptionTestCase.java    From velocity-engine with Apache License 2.0 6 votes vote down vote up
public void testMethodException() throws Exception
{

    // accumulate a list of invalid references
    Context context = new VelocityContext();
    StringWriter writer = new StringWriter();
    context.put("test",new TestProvider());

    try
    {
        ve.evaluate(context,writer,"test","$test.getThrow()");
        fail ("expected an exception");
    }
    catch (MethodInvocationException E)
    {
        assertEquals(Exception.class,E.getCause().getClass());
        assertEquals("From getThrow()",E.getCause().getMessage());
    }

}
 
Example #13
Source File: Velocity.java    From velocity-engine with Apache License 2.0 6 votes vote down vote up
/**
 *  Merges a template and puts the rendered stream into the writer
 *
 *  @param templateName name of template to be used in merge
 *  @param encoding encoding used in template
 *  @param context  filled context to be used in merge
 *  @param  writer  writer to write template into
 *
 *  @return true if successful, false otherwise.  Errors
 *           logged to velocity log
 *
 * @throws ParseErrorException The template could not be parsed.
 * @throws MethodInvocationException A method on a context object could not be invoked.
 * @throws ResourceNotFoundException A referenced resource could not be loaded.
 *
 * @since Velocity v1.1
 */
public static boolean mergeTemplate( String templateName, String encoding,
                                  Context context, Writer writer )
    throws ResourceNotFoundException, ParseErrorException, MethodInvocationException
{
    Template template = RuntimeSingleton.getTemplate(templateName, encoding);

    if ( template == null )
    {
        String msg = "Velocity.mergeTemplate() was unable to load template '"
                       + templateName + "'";
        getLog().error(msg);
        throw new ResourceNotFoundException(msg);
    }
    else
    {
        template.merge(context, writer);
        return true;
    }
}
 
Example #14
Source File: Page.java    From bazel with Apache License 2.0 6 votes vote down vote up
/**
 * Renders the template and writes the output to the given file.
 *
 * Strips all trailing whitespace before writing to file.
 */
public void write(File outputFile) throws IOException {
  StringWriter stringWriter = new StringWriter();
  try {
    engine.mergeTemplate(template, "UTF-8", context, stringWriter);
  } catch (ResourceNotFoundException|ParseErrorException|MethodInvocationException e) {
    throw new IOException(e);
  }
  stringWriter.close();

  String[] lines = stringWriter.toString().split(System.getProperty("line.separator"));
  try (Writer fileWriter = Files.newBufferedWriter(outputFile.toPath(), UTF_8)) {
    for (String line : lines) {
      // Strip trailing whitespace then append newline before writing to file.
      fileWriter.write(line.replaceFirst("\\s+$", "") + "\n");
    }
  }
}
 
Example #15
Source File: MarkdownRenderer.java    From bazel with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a markdown rendering of provider documentation for the given provider information
 * object with the given name.
 */
public String render(String providerName, ProviderInfo providerInfo) throws IOException {
  VelocityContext context = new VelocityContext();
  context.put("util", new MarkdownUtil());
  context.put("providerName", providerName);
  context.put("providerInfo", providerInfo);

  StringWriter stringWriter = new StringWriter();
  Reader reader = readerFromPath(providerTemplateFilename);
  try {
    velocityEngine.evaluate(context, stringWriter, providerTemplateFilename, reader);
  } catch (ResourceNotFoundException | ParseErrorException | MethodInvocationException e) {
    throw new IOException(e);
  }
  return stringWriter.toString();
}
 
Example #16
Source File: MarkdownRenderer.java    From bazel with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a markdown rendering of rule documentation for the given rule information object with
 * the given rule name.
 */
public String render(String ruleName, RuleInfo ruleInfo) throws IOException {
  VelocityContext context = new VelocityContext();
  context.put("util", new MarkdownUtil());
  context.put("ruleName", ruleName);
  context.put("ruleInfo", ruleInfo);

  StringWriter stringWriter = new StringWriter();
  Reader reader = readerFromPath(ruleTemplateFilename);
  try {
    velocityEngine.evaluate(context, stringWriter, ruleTemplateFilename, reader);
  } catch (ResourceNotFoundException | ParseErrorException | MethodInvocationException e) {
    throw new IOException(e);
  }
  return stringWriter.toString();
}
 
Example #17
Source File: ASTReference.java    From velocity-engine with Apache License 2.0 6 votes vote down vote up
/**
 *   Computes boolean value of this reference
 *   Returns the actual value of reference return type
 *   boolean, and 'true' if value is not null
 *
 *   @param context context to compute value with
 * @return True if evaluation was ok.
 * @throws MethodInvocationException
 */
public boolean evaluate(InternalContextAdapter context)
    throws MethodInvocationException
{
    Object value = execute(this, context); // non-null object as first parameter by convention for 'evaluate'
    if (value == null)
    {
        return false;
    }
    try
    {
        rsvc.getLogContext().pushLogContext(this, uberInfo);
        return DuckType.asBoolean(value, checkEmpty);
    }
    catch(Exception e)
    {
        throw new VelocityException("Reference evaluation threw an exception at "
            + StringUtils.formatFileString(this), e, rsvc.getLogContext().getStackTrace());
    }
    finally
    {
        rsvc.getLogContext().popLogContext();
    }
}
 
Example #18
Source File: JspUtilsTest.java    From velocity-tools with Apache License 2.0 6 votes vote down vote up
/**
 * Test method for {@link org.apache.velocity.tools.view.jsp.jspimpl.JspUtils#executeTag(org.apache.velocity.context.InternalContextAdapter, org.apache.velocity.runtime.parser.node.Node, javax.servlet.jsp.PageContext, javax.servlet.jsp.tagext.Tag)}.
 * @throws JspException If something goes wrong.
 * @throws IOException If something goes wrong.
 * @throws ParseErrorException If something goes wrong.
 * @throws ResourceNotFoundException If something goes wrong.
 * @throws MethodInvocationException If something goes wrong.
 */
@Test
public void testExecuteTag() throws JspException, MethodInvocationException, ResourceNotFoundException, ParseErrorException, IOException
{
    InternalContextAdapter context = createMock(InternalContextAdapter.class);
    Node node = createMock(Node.class);
    PageContext pageContext = createMock(PageContext.class);
    BodyTag tag = createMock(BodyTag.class);
    ASTBlock block = createMock(ASTBlock.class);
    JspWriter writer = createMock(JspWriter.class);

    expect(tag.doStartTag()).andReturn(BodyTag.EVAL_BODY_BUFFERED);
    tag.setBodyContent(isA(VelocityBodyContent.class));
    tag.doInitBody();
    expect(node.jjtGetChild(1)).andReturn(block);
    expect(tag.doAfterBody()).andReturn(BodyTag.SKIP_BODY);
    expect(tag.doEndTag()).andReturn(BodyTag.EVAL_PAGE);
    expect(pageContext.getOut()).andReturn(writer);
    expect(block.render(eq(context), isA(StringWriter.class))).andReturn(true);

    replay(context, node, pageContext, block, tag, writer);
    JspUtils.executeTag(context, node, pageContext, tag);
    verify(context, node, pageContext, block, tag, writer);
}
 
Example #19
Source File: XmlCompressorDirective.java    From htmlcompressor with Apache License 2.0 6 votes vote down vote up
public boolean render(InternalContextAdapter context, Writer writer, Node node) 
  		throws IOException, ResourceNotFoundException, ParseErrorException, MethodInvocationException {
  	
  	//render content
  	StringWriter content = new StringWriter();
node.jjtGetChild(0).render(context, content);

//compress
try {
	writer.write(xmlCompressor.compress(content.toString()));
} catch (Exception e) {
	writer.write(content.toString());
	String msg = "Failed to compress content: "+content.toString();
          log.error(msg, e);
          throw new RuntimeException(msg, e);
          
}
return true;
  	
  }
 
Example #20
Source File: HtmlCompressorDirective.java    From htmlcompressor with Apache License 2.0 6 votes vote down vote up
public boolean render(InternalContextAdapter context, Writer writer, Node node) 
  		throws IOException, ResourceNotFoundException, ParseErrorException, MethodInvocationException {
  	
  	//render content
  	StringWriter content = new StringWriter();
node.jjtGetChild(0).render(context, content);

//compress
try {
	writer.write(htmlCompressor.compress(content.toString()));
} catch (Exception e) {
	writer.write(content.toString());
	String msg = "Failed to compress content: "+content.toString();
          log.error(msg, e);
          throw new RuntimeException(msg, e);
          
}
return true;
  	
  }
 
Example #21
Source File: VelocityGenerator.java    From celerio with Apache License 2.0 6 votes vote down vote up
public String evaluate(Map<String, Object> context, TemplatePack templatePack, Template template) throws IOException {
    StringWriter sw = new StringWriter();
    try {
        engine.evaluate(new VelocityContext(context), sw, template.getName(), template.getTemplate());
        return sw.toString();
    } catch (ParseErrorException parseException) {
        handleStopFileGeneration(parseException);
        log.error("In " + templatePack.getName() + ":" + template.getName() + " template, parse exception " + parseException.getMessage(),
                parseException.getCause());
        displayLinesInError(parseException, templatePack, template);
        throw new IllegalStateException();
    } catch (MethodInvocationException mie) {
        handleStopFileGeneration(mie);
        log.error("In " + templatePack.getName() + ":" + mie.getTemplateName() + " method [" + mie.getMethodName() + "] has not been set", mie.getCause());
        displayLinesInError(mie, templatePack, template);
        throw mie;
    } finally {
        closeQuietly(sw);
    }
}
 
Example #22
Source File: ASTObjectArray.java    From velocity-engine with Apache License 2.0 6 votes vote down vote up
/**
 * @see org.apache.velocity.runtime.parser.node.SimpleNode#value(org.apache.velocity.context.InternalContextAdapter)
 */
public Object value( InternalContextAdapter context)
    throws MethodInvocationException
{
    int size = jjtGetNumChildren();

    // since we know the amount of elements, initialize arraylist with proper size
    List objectArray = new ArrayList(size);

    for (int i = 0; i < size; i++)
    {
        objectArray.add(jjtGetChild(i).value(context));
    }

    return objectArray;
}
 
Example #23
Source File: Include.java    From velocity-engine with Apache License 2.0 5 votes vote down vote up
/**
 *  iterates through the argument list and renders every
 *  argument that is appropriate.  Any non appropriate
 *  arguments are logged, but render() continues.
 * @param context
 * @param writer
 * @param node
 * @return True if the directive rendered successfully.
 * @throws IOException
 * @throws MethodInvocationException
 * @throws ResourceNotFoundException
 */
public boolean render(InternalContextAdapter context,
                       Writer writer, Node node)
    throws IOException, MethodInvocationException,
           ResourceNotFoundException
{
    /*
     *  get our arguments and check them
     */

    int argCount = node.jjtGetNumChildren();

    for( int i = 0; i < argCount; i++)
    {
        /*
         *  we only handle StringLiterals and References right now
         */

        Node n = node.jjtGetChild(i);

        if ( n.getType() ==  ParserTreeConstants.JJTSTRINGLITERAL ||
             n.getType() ==  ParserTreeConstants.JJTREFERENCE )
        {
            if (!renderOutput( n, context, writer ))
                outputErrorToStream( writer, "error with arg " + i
                    + " please see log.");
        }
        else
        {
            String msg = "invalid #include() argument '"
              + n.toString() + "' at " + StringUtils.formatFileString(this);
            log.error(msg);
            outputErrorToStream( writer, "error with arg " + i
                + " please see log.");
            throw new VelocityException(msg, null, rsvc.getLogContext().getStackTrace());
        }
    }

    return true;
}
 
Example #24
Source File: VelocityWrapper.java    From consulo with Apache License 2.0 5 votes vote down vote up
static boolean evaluate(@Nullable Project project, Context context, Writer writer, String templateContent)
        throws ParseErrorException, MethodInvocationException, ResourceNotFoundException {
  try {
    ourTemplateManager.set(project == null ? FileTemplateManager.getDefaultInstance() : FileTemplateManager.getInstance(project));
    return Velocity.evaluate(context, writer, "", templateContent);
  }
  finally {
    ourTemplateManager.set(null);
  }
}
 
Example #25
Source File: ConfigurableLDAPResolver.java    From XACML with MIT License 5 votes vote down vote up
private String evaluateVelocityTemplate(String template,
		final Map<String,PIPRequest> templateParameters,
		final PIPEngine pipEngine,
		final PIPFinder pipFinder) 
				throws PIPException {
	StringWriter out = new StringWriter();
	VelocityContext vctx = new VelocityContext();
	EventCartridge vec = new EventCartridge();
	VelocityParameterWriter writer = new VelocityParameterWriter(
			pipEngine, pipFinder, templateParameters);
	vec.addEventHandler(writer);
	vec.attachToContext(vctx);

	try {
		Velocity.evaluate(vctx, out,
				"LdapResolver", template);
	}
	catch (ParseErrorException pex) {
		throw new PIPException(
				"Velocity template evaluation failed",pex);
	}
	catch (MethodInvocationException mix) {
		throw new PIPException(
				"Velocity template evaluation failed",mix);
	}
	catch (ResourceNotFoundException rnfx) {
		throw new PIPException(
				"Velocity template evaluation failed",rnfx);
	}

	this.logger.warn("(" + id + ") " + " template yields " + out.toString());

	return out.toString();
}
 
Example #26
Source File: IntrospectionCacheDataTestCase.java    From velocity-engine with Apache License 2.0 5 votes vote down vote up
public void testCache() throws ParseErrorException, MethodInvocationException,
ResourceNotFoundException, IOException
{
    CacheHitCountingVelocityContext context = new CacheHitCountingVelocityContext();
    context.put("this", this);
    StringWriter w = new StringWriter();
    Velocity.evaluate(context, w, "test", "$this.exec('a')$this.exec('b')");
    assertEquals("[a][b]", w.toString());
    assertTrue(context.cacheHit > 0);
}
 
Example #27
Source File: ASTReference.java    From velocity-engine with Apache License 2.0 5 votes vote down vote up
/**
 * @param context
 * @return The evaluated value of the variable.
 * @throws MethodInvocationException
 */
public Object getRootVariableValue(InternalContextAdapter context)
{
    Object obj = null;
    try
    {
        obj = context.get(rootString);
    }
    catch(RuntimeException e)
    {
        log.error("Exception calling reference ${} at {}",
                  rootString, StringUtils.formatFileString(uberInfo));
        throw e;
    }

    if (obj == null && strictRef && astAlternateValue == null)
    {
      if (!context.containsKey(rootString))
      {
          log.error("Variable ${} has not been set at {}",
                    rootString, StringUtils.formatFileString(uberInfo));
          throw new MethodInvocationException("Variable $" + rootString +
              " has not been set", null, rsvc.getLogContext().getStackTrace(), identifier,
              uberInfo.getTemplateName(), uberInfo.getLine(), uberInfo.getColumn());
      }
    }
    return obj;
}
 
Example #28
Source File: ASTAndNode.java    From velocity-engine with Apache License 2.0 5 votes vote down vote up
/**
 * logical and :
 * <pre>
 *   null &amp;&amp; right = false
 *   left &amp;&amp; null = false
 *   null &amp;&amp; null = false
 * </pre>
 * @param context
 * @return True if both sides are true.
 * @throws MethodInvocationException
 */
public boolean evaluate( InternalContextAdapter context)
    throws MethodInvocationException
{
    Node left = jjtGetChild(0);
    Node right = jjtGetChild(1);

    /*
     * null == false
     */
    if (left == null || right == null)
    {
        return false;
    }

    /*
     *  short circuit the test.  Don't eval the RHS if the LHS is false
     */

    if( left.evaluate( context ) )
    {
        if ( right.evaluate( context ) )
        {
            return true;
        }
    }

    return false;
}
 
Example #29
Source File: ExceptionTestCase.java    From velocity-engine with Apache License 2.0 5 votes vote down vote up
public void assertMethodInvocationException(VelocityEngine ve, Context context, String input)
throws Exception
{
    try
    {
        StringWriter writer = new StringWriter();
        ve.evaluate(context,writer,"test",input);
        fail("Expected MethodInvocationException");
    }
    catch (MethodInvocationException E)
    {
        // do nothing
    }
}
 
Example #30
Source File: ASTElseIfStatement.java    From velocity-engine with Apache License 2.0 5 votes vote down vote up
/**
 * @see org.apache.velocity.runtime.parser.node.SimpleNode#render(org.apache.velocity.context.InternalContextAdapter, java.io.Writer)
 */
public boolean render( InternalContextAdapter context, Writer writer)
    throws IOException,MethodInvocationException,
    	ResourceNotFoundException, ParseErrorException
{
    return jjtGetChild(1).render( context, writer );
}