org.apache.velocity.util.introspection.Info Java Examples

The following examples show how to use org.apache.velocity.util.introspection.Info. 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: EventHandlingTestCase.java    From velocity-engine with Apache License 2.0 6 votes vote down vote up
/**
 *  Handles exceptions thrown during in-template method access
 */
public Object methodException( Context context, Class claz, String method, Exception e, Info info )
{
    // as a test, make sure this EventHandler is initialized
    if (rs == null)
        fail ("Event handler not initialized!");

    // only do processing if the switch is on
    if (context != null)
    {
        boolean exceptionSwitch = context.containsKey("allow_exception");

        if( exceptionSwitch && method.equals("throwException"))
        {
            return "handler";
        }
        else
            throw new RuntimeException(e);

    } else

        throw new RuntimeException(e);
}
 
Example #2
Source File: AgnVelocityUberspector.java    From openemm with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Checks the method call from Velocity script.
 * 
 * @param callee objects thats method is called 
 * @param methodName name of the called method
 * @param args arguments
 * @param info information on template
 * 
 * @throws VelocityCheckerException 
 */
private void checkMethodAccess( Object callee, String methodName, Object[] args, Info info) {
	if( callee != null) {
		Method method = introspector.getMethod( callee.getClass(), methodName, args);
		
		if( method != null) {
			checkMethodAccess( method, args, info);
		} else {
			if( logger.isInfoEnabled())
				logger.info( "No matching method name " + methodName + " found for given argument types - skipping checks");
		}
	} else {
		try {
			throw new RuntimeException( "Cannot check null reference");
		} catch( RuntimeException e) {
			logger.warn( "Performing access check on null reference", e);
		}
	}
}
 
Example #3
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 #4
Source File: InvalidEventHandlerTestCase.java    From velocity-engine with Apache License 2.0 6 votes vote down vote up
public boolean invalidSetMethod(Context context, String leftreference, String rightreference, Info info)
{

    // as a test, make sure this EventHandler is initialized
    if (rs == null)
        fail ("Event handler not initialized!");

    // good object, bad method
    if (leftreference.equals("xx"))
    {
        assertEquals("q1.afternoon()",rightreference);
        throw new RuntimeException("expected exception");
    }
    if (leftreference.equals("yy"))
    {
        assertEquals("$q1",rightreference);
        throw new RuntimeException("expected exception");
    }
    else
    {
        fail("Unexpected left hand side.  " + leftreference);
    }

    return false;
}
 
Example #5
Source File: InvalidEventHandlerTestCase.java    From velocity-engine with Apache License 2.0 6 votes vote down vote up
public Object invalidMethod(Context context, String reference, Object object, String method, Info info)
{
    // as a test, make sure this EventHandler is initialized
    if (rs == null)
        fail ("Event handler not initialized!");

    // good reference, bad method
    if (object.getClass().equals(Integer.class))
    {
        assertEquals("$a1.afternoon()",reference);
        assertEquals("afternoon",method);
        throw new RuntimeException("expected exception");
    }

    else if (object.getClass().equals(String.class) && "baby".equals(method))
    {
        return "www";
    }

    else
    {
        fail("Unexpected invalid method.  " + method);
    }

    return null;
}
 
Example #6
Source File: InfoTestCase.java    From velocity-engine with Apache License 2.0 6 votes vote down vote up
public void checkInfo(String templateName,
        int expectedLine, int expectedCol) throws Exception
{
    Context context = new VelocityContext();
    Template template = ve.getTemplate(templateName, "UTF-8");
    Info info = null;

    context.put("main", this);

    try (StringWriter writer = new StringWriter())
    {
        template.merge(context, writer);
        writer.flush();
        fail("Uberspect should have thrown an exception");
    }
    catch (UberspectTestException E)
    {
        info = E.getInfo();
    }
    assertInfoEqual(info, templateName, expectedLine, expectedCol);

}
 
Example #7
Source File: TestableUberspect.java    From ApprovalTests.Java with Apache License 2.0 6 votes vote down vote up
public static Iterator<?> getStandardIterator(Object obj, Info i)
{
  if (obj.getClass().isArray())
  {
    return new ArrayIterator(obj);
  }
  else if (obj instanceof Collection)
  {
    return ((Collection<?>) obj).iterator();
  }
  else if (obj instanceof Map)
  {
    return ((Map<?, ?>) obj).values().iterator();
  }
  else if (obj instanceof Iterator)
  {
    return ((Iterator<?>) obj);
  }
  else if (obj instanceof Enumeration)
  { return new EnumerationIterator((Enumeration<?>) obj); }
  throw new VelocityParsingError("Could not determine type of iterator in " + "#foreach loop ", i);
}
 
Example #8
Source File: TestableUberspect.java    From ApprovalTests.Java with Apache License 2.0 6 votes vote down vote up
public VelMethod getMethod(Object obj, String methodName, Object[] args, Info i) throws Exception
{
  if (obj == null)
  {
    if (beKindToNulls)
    {
      return null;
    }
    else
    {
      throw new VelocityParsingError("tried " + getMethodText("null", methodName, args), i);
    }
  }
  Method m = introspector.getMethod(obj.getClass(), methodName, args);
  if (m == null)
  {
    throw new VelocityParsingError(
        "Method " + getMethodText(obj.getClass().getName(), methodName, args) + " does not exist.", i);
  }
  return new VelMethodImpl(m);
}
 
Example #9
Source File: TestableUberspect.java    From ApprovalTests.Java with Apache License 2.0 6 votes vote down vote up
public VelPropertyGet getPropertyGet(Object obj, String identifier, Info i) throws Exception
{
  AbstractExecutor executor;
  if (obj == null)
  { throw new VelocityParsingError("tried " + getPropertyText("null", identifier), i); }
  Class<? extends Object> claz = obj.getClass();
  // trying getFoo()
  executor = new PropertyExecutor(log, introspectorWithLog, claz, identifier);
  if (!executor.isAlive())
  {
    // trying  get("foo")
    executor = new GetExecutor(log, introspectorWithLog, claz, identifier);
  }
  if (!executor.isAlive())
  {
    // trying  isFoo()
    executor = new BooleanPropertyExecutor(log, introspectorWithLog, claz, identifier);
  }
  if (!executor.isAlive())
  { throw new VelocityParsingError("Did not find " + getPropertyText(obj.getClass().getName(), identifier), i); }
  return new VelGetterImpl(executor);
}
 
Example #10
Source File: WebappUberspector.java    From velocity-tools with Apache License 2.0 6 votes vote down vote up
/**
 * Property getter
 * @param obj target object
 * @param identifier property key
 * @param i tool info
 * @return A Velocity Getter Method.
 */
public VelPropertyGet getPropertyGet(Object obj, String identifier, Info i)
{
    if (obj == null)
    {
        return null;
    }
    VelPropertyGet ret = super.getPropertyGet(obj,identifier,i);

    if(ret == null)
    {
        Class claz = obj.getClass();
        if(obj instanceof HttpServletRequest
            || obj instanceof HttpSession
            || obj instanceof ServletContext)
        {
            AbstractExecutor executor = new GetAttributeExecutor(log, introspector, claz, identifier);
            ret = executor.isAlive() ? new VelGetterImpl(executor) : null;
        }
    }
    return ret;
}
 
Example #11
Source File: WebappUberspector.java    From velocity-tools with Apache License 2.0 6 votes vote down vote up
/**
 * Property setter
 * @param obj target object
 * @param identifier property key
 * @param arg value to set
 * @param i tool info
 * @return A Velocity Setter method.
 */
public VelPropertySet getPropertySet(Object obj, String identifier,
                                     Object arg, Info i)
{
    if (obj == null)
    {
        return null;
    }
    VelPropertySet ret = super.getPropertySet(obj,identifier,arg,i);

    if(ret == null) {
        Class claz = obj.getClass();
        if(obj instanceof HttpServletRequest
            || obj instanceof HttpSession
            || obj instanceof ServletContext)
        {
            SetExecutor executor = new SetAttributeExecutor(log, introspector, claz, arg, identifier);
            ret = executor.isAlive() ? new VelSetterImpl(executor) : null;
        }
    }
    return ret;
}
 
Example #12
Source File: PrintExceptions.java    From velocity-engine with Apache License 2.0 6 votes vote down vote up
/**
 * Render the method exception, and optionally the exception message and stack trace.
 *
 * @param context current context
 * @param claz the class of the object the method is being applied to
 * @param method the method
 * @param e the thrown exception
 * @param info template name and line, column informations
 * @return an object to insert in the page
 */
public Object methodException(Context context, Class claz, String method, Exception e, Info info)
{
    boolean showTemplateInfo = rs.getBoolean(SHOW_TEMPLATE_INFO, false);
    boolean showStackTrace = rs.getBoolean(SHOW_STACK_TRACE,false);

    StringBuilder st = new StringBuilder();
    st.append("Exception while executing method ").append(claz.toString()).append(".").append(method);
    st.append(": ").append(e.getClass().getName()).append(": ").append(e.getMessage());

    if (showTemplateInfo)
    {
        st.append(" at ").append(info.getTemplateName()).append(" (line ").append(info.getLine()).append(", column ").append(info.getColumn()).append(")");
    }
    if (showStackTrace)
    {
        st.append(System.lineSeparator()).append(getStackTrace(e));
    }
    return st.toString();

}
 
Example #13
Source File: LogContext.java    From velocity-engine with Apache License 2.0 6 votes vote down vote up
public void pushLogContext(SimpleNode src, Info info)
{
    if (!trackLocation)
    {
        return;
    }
    Deque<StackElement> stack = contextStack.get();
    StackElement last = stack.peek();
    if (last != null && last.src == src)
    {
        ++last.count;
    }
    else
    {
        stack.push(new StackElement(src, info));
        setLogContext(info);
    }
}
 
Example #14
Source File: ASTIdentifier.java    From velocity-engine with Apache License 2.0 6 votes vote down vote up
/**
 *  simple init - don't do anything that is context specific.
 *  just get what we need from the AST, which is static.
 * @param context
 * @param data
 * @return The data object.
 * @throws TemplateInitException
 */
public  Object init(InternalContextAdapter context, Object data)
    throws TemplateInitException
{
    super.init(context, data);

    identifier = rsvc.useStringInterning() ? getFirstToken().image.intern() : getFirstToken().image;

    uberInfo = new Info(getTemplateName(), getLine(), getColumn());

    strictRef = rsvc.getBoolean(RuntimeConstants.RUNTIME_REFERENCES_STRICT, false);

    saveTokenImages();
    cleanupParserAndTokens();

    return data;
}
 
Example #15
Source File: ASTMethod.java    From velocity-engine with Apache License 2.0 6 votes vote down vote up
/**
 *  simple init - init our subtree and get what we can from
 *  the AST
 * @param context
 * @param data
 * @return The init result
 * @throws TemplateInitException
 */
public Object init(  InternalContextAdapter context, Object data)
    throws TemplateInitException
{
    super.init(  context, data );

    /*
     * make an uberinfo - saves new's later on
     */

    uberInfo = new Info(getTemplateName(),
            getLine(),getColumn());
    /*
     *  this is about all we can do
     */

    methodName = getFirstToken().image;
    paramCount = jjtGetNumChildren() - 1;

    strictRef = rsvc.getBoolean(RuntimeConstants.RUNTIME_REFERENCES_STRICT, false);
    logOnInvalid = rsvc.getBoolean(RuntimeConstants.RUNTIME_LOG_METHOD_CALL_LOG_INVALID, true);

    cleanupParserAndTokens();

    return data;
}
 
Example #16
Source File: ParseErrorException.java    From velocity-engine with Apache License 2.0 5 votes vote down vote up
/**
 * Create a ParseErrorRuntimeException with the given message and info
 *
 * @param exceptionMessage the error exception message
 * @param info an Info object with the current template info
 * @since 2.2
 */
public ParseErrorException(String exceptionMessage, Info info, String[] stacktrace)
{
    super(exceptionMessage, null, stacktrace);
    columnNumber = info.getColumn();
    lineNumber = info.getLine();
    templateName = info.getTemplateName();
}
 
Example #17
Source File: UberspectTestImpl.java    From velocity-engine with Apache License 2.0 5 votes vote down vote up
public VelMethod getMethod(Object obj, String methodName, Object[] args, Info i)
{
    VelMethod method = super.getMethod(obj, methodName, args, i);

    if (method == null)
    {
        if (obj == null)
            throw new UberspectTestException("Can't call method '" + methodName + "' on null object",i);
        else
            throw new UberspectTestException("Did not find method "+ obj.getClass().getName()+"."+methodName, i);
    }

    return method;
}
 
Example #18
Source File: UberspectTestImpl.java    From velocity-engine with Apache License 2.0 5 votes vote down vote up
public VelPropertyGet getPropertyGet(Object obj, String identifier, Info i)
{
    VelPropertyGet propertyGet = super.getPropertyGet(obj, identifier, i);

    if (propertyGet == null)
    {
        if (obj == null)
            throw new UberspectTestException("Can't call getter '" + identifier + "' on null object",i);
        else
            throw new UberspectTestException("Did not find "+ obj.getClass().getName()+"."+identifier, i);
    }

    return propertyGet;
}
 
Example #19
Source File: ConversionHandlerTestCase.java    From velocity-engine with Apache License 2.0 5 votes vote down vote up
public Object methodException(Context context,
                              Class claz,
                              String method,
                              Exception e,
                              Info info)
{
    return method + " -> " + e.getClass().getSimpleName() + ": " + e.getMessage();
}
 
Example #20
Source File: ParseErrorException.java    From velocity-engine with Apache License 2.0 5 votes vote down vote up
/**
 * Create a ParseErrorRuntimeException with the given message and info
 *
 * @param exceptionMessage the error exception message
 * @param info an Info object with the current template info
 * @since 1.5
 */
public ParseErrorException(String exceptionMessage, Info info)
{
    super(exceptionMessage);
    columnNumber = info.getColumn();
    lineNumber = info.getLine();
    templateName = info.getTemplateName();
}
 
Example #21
Source File: EventExample.java    From velocity-engine with Apache License 2.0 5 votes vote down vote up
public Object methodException( Context context, Class claz, String method, Exception e, Info info )   {
    /*
     *  only do processing if the switch is on
     */

    if( exceptionSwitch && method.equals("throwException"))
    {
        return "Hello from the methodException() event handler method.";
    }

    throw new RuntimeException(e);
}
 
Example #22
Source File: EventHandlerUtil.java    From velocity-engine with Apache License 2.0 5 votes vote down vote up
/**
 * Called when a method exception is generated during Velocity merge. Only
 * the first valid event handler in the sequence is called. The default
 * implementation simply rethrows the exception.
 *
 * @param claz
 *            Class that is causing the exception
 * @param method
 *            method called that causes the exception
 * @param e
 *            Exception thrown by the method
 * @param rsvc current instance of RuntimeServices
 * @param context The internal context adapter.
 * @param info exception location informations
 * @return Object to return as method result
 * @throws Exception
 *             to be wrapped and propagated to app
 */
public static Object methodException(RuntimeServices rsvc,
        InternalContextAdapter context, Class claz, String method,
        Exception e, Info info) throws Exception
{
    try
    {
        EventCartridge ev = rsvc.getApplicationEventCartridge();
        if (ev.hasMethodExceptionEventHandler())
        {
            return ev.methodException(context, claz, method, e, info);
        }
        EventCartridge contextCartridge = context.getEventCartridge();
        if (contextCartridge != null)
        {
            contextCartridge.setRuntimeServices(rsvc);
            return contextCartridge.methodException(context, claz, method, e, info);
        }
    }
    catch (RuntimeException re)
    {
        throw re;
    }
    catch (Exception ex)
    {
        throw new VelocityException("Exception in event handler.", ex, rsvc.getLogContext().getStackTrace());
    }

    /* default behaviour is to re-throw exception */
    throw e;
}
 
Example #23
Source File: EventCartridge.java    From velocity-engine with Apache License 2.0 5 votes vote down vote up
/**
 * Call invalid reference handlers for an invalid getter
 *
 * @param context
 * @param reference
 * @param object
 * @param property
 * @param info
 * @return value returned by handlers
 * @since 2.0
 */
public Object invalidGetMethod(Context context, String reference, Object object, String property, Info info)
{
    Object result = null;
    for (InvalidReferenceEventHandler handler : invalidReferenceHandlers)
    {
        result = handler.invalidGetMethod(context, reference, object, property, info);
          /* reflect 1.x behavior: exit after at least one execution whenever a non-null value has been found */
        if (result != null)
        {
            break;
        }
    }
    return result;
}
 
Example #24
Source File: EventCartridge.java    From velocity-engine with Apache License 2.0 5 votes vote down vote up
/**
 * Call invalid reference handlers for an invalid setter
 *
 * @param context
 * @param leftreference
 * @param rightreference
 * @param info
 * @return whether to stop further chaining in the next cartridge
 * @since 2.0
 */
public boolean invalidSetMethod(Context context, String leftreference, String rightreference, Info info)
{
    for (InvalidReferenceEventHandler handler : invalidReferenceHandlers)
    {
        if (handler.invalidSetMethod(context, leftreference, rightreference, info))
        {
            return true;
        }
    }
    return false;
}
 
Example #25
Source File: EventCartridge.java    From velocity-engine with Apache License 2.0 5 votes vote down vote up
/**
 * Call invalid reference handlers for an invalid method call
 *
 * @param context
 * @param reference
 * @param object
 * @param method
 * @param info
 * @return value returned by handlers
 * @since 2.0
 */
public Object invalidMethod(Context context, String reference, Object object, String method, Info info)
{
    Object result = null;
    for (InvalidReferenceEventHandler handler : invalidReferenceHandlers)
    {
        result = handler.invalidMethod(context, reference, object, method, info);
          /* reflect 1.x behavior: exit after at least one execution whenever a non-null value has been found */
        if (result != null)
        {
            break;
        }
    }
    return result;
}
 
Example #26
Source File: AgnVelocityUberspector.java    From openemm with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public VelPropertySet getPropertySet(Object obj, String identifier, Object arg, Info info) throws Exception {
	
	if( isRuntimeCheckEnabled()) {
		checkRestrictedPackage( obj);

		if( this.packageChecker.includePackage( obj.getClass().getPackage())) {
			checkPropertyWriteAccess( obj, identifier, arg, info);
		}
	}
	
	return super.getPropertySet(obj, identifier, arg, info);
}
 
Example #27
Source File: ReportInvalidReferences.java    From velocity-engine with Apache License 2.0 5 votes vote down vote up
/**
 * Collect the error and/or throw an exception, depending on configuration.
 *
 * @param context the context when the reference was found invalid
 * @param reference complete invalid reference
 * @param object the object referred to, or null if not found
 * @param method the property name from the reference
 * @param info contains template, line, column details
 * @return always returns null
 * @throws ParseErrorException
 */
public Object invalidMethod(Context context, String reference, Object object,
        String method, Info info)
{
    if (reference == null)
    {
        reportInvalidReference(object.getClass().getName() + "." + method, info);
    }
    else
    {
        reportInvalidReference(reference, info);
    }
    return null;
}
 
Example #28
Source File: ReportInvalidReferences.java    From velocity-engine with Apache License 2.0 5 votes vote down vote up
/**
 * Check for an invalid reference and collect the error or throw an exception
 * (depending on configuration).
 *
 * @param reference the invalid reference
 * @param info line, column, template name
 */
private void reportInvalidReference(String reference, Info info)
{
    InvalidReferenceInfo invalidReferenceInfo = new InvalidReferenceInfo(reference, info);
    invalidReferences.add(invalidReferenceInfo);

    if (stopOnFirstInvalidReference)
    {
        throw new ParseErrorException(
                "Error in page - invalid reference.  ",
                info,
                invalidReferenceInfo.getInvalidReference());
    }
}
 
Example #29
Source File: AgnVelocityUberspector.java    From openemm with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public VelMethod getMethod(Object obj, String methodName, Object[] args, Info info) throws Exception {
	
	if( isRuntimeCheckEnabled()) {
		checkRestrictedPackage( obj);

		if( this.packageChecker.includePackage( obj.getClass().getPackage())) {
			checkMethodAccess( obj, methodName, args, info);
		}
	}
	
	return super.getMethod(obj, methodName, args, info);
}
 
Example #30
Source File: EventExample.java    From velocity-engine with Apache License 2.0 5 votes vote down vote up
/**
 *  Event handler for when the right hand side of
 *  a #set() directive is null, which results in
 *  a log message.  This method gives the application
 *  a chance to 'vote' on msg generation
 */
public boolean invalidSetMethod(Context context, String leftreference, String rightreference, Info info)
{
    if (leftreference.equals("logthis"))
    {
        System.out.print("Setting reference " + leftreference + " to null");
    }
    return false;
}