Search in sources :

Example 1 with MethodInvocationException

use of org.apache.velocity.exception.MethodInvocationException in project jena by apache.

the class SimpleVelocity method process.

/** Process a template */
public static void process(String base, String path, Writer out, VelocityContext context) {
    VelocityEngine velocity = new VelocityEngine();
    // Turn off logging - catch exceptions and log ourselves
    velocity.setProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM, velocityLogChute);
    velocity.setProperty(RuntimeConstants.INPUT_ENCODING, "UTF-8");
    velocity.setProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, base);
    velocity.init();
    try {
        Template temp = velocity.getTemplate(path);
        temp.merge(context, out);
        out.flush();
    } catch (ResourceNotFoundException ex) {
        velocityLog.error("Resource not found: " + ex.getMessage());
    } catch (ParseErrorException ex) {
        velocityLog.error("Parse error (" + path + ") : " + ex.getMessage());
    } catch (MethodInvocationException ex) {
        velocityLog.error("Method invocation exception (" + path + ") : " + ex.getMessage());
    } catch (IOException ex) {
        velocityLog.warn("IOException", ex);
    }
}
Also used : VelocityEngine(org.apache.velocity.app.VelocityEngine) ParseErrorException(org.apache.velocity.exception.ParseErrorException) MethodInvocationException(org.apache.velocity.exception.MethodInvocationException) IOException(java.io.IOException) ResourceNotFoundException(org.apache.velocity.exception.ResourceNotFoundException) Template(org.apache.velocity.Template)

Example 2 with MethodInvocationException

use of org.apache.velocity.exception.MethodInvocationException in project herd by FINRAOS.

the class StorageUnitServiceGetS3KeyPrefixTest method testGetS3KeyPrefixUndefinedVelocityVariable.

@Test
public void testGetS3KeyPrefixUndefinedVelocityVariable() {
    // Create database entities required for testing.
    businessObjectDataServiceTestHelper.createDatabaseEntitiesForGetS3KeyPrefixTesting(true);
    // Get the test partition columns.
    List<SchemaColumn> testPartitionColumns = schemaColumnDaoTestHelper.getTestPartitionColumns();
    String testPartitionKey = testPartitionColumns.get(0).getName();
    // Create an undefined velocity variable.
    String undefinedVelocityVariable = "$UNDEFINED_VARIABLE";
    // Create an S3 storage entity with the S3 key prefix template containing an undefined variable.
    storageDaoTestHelper.createStorageEntity(STORAGE_NAME_2, StoragePlatformEntity.S3, Arrays.asList(new Attribute(configurationHelper.getProperty(ConfigurationValue.S3_ATTRIBUTE_NAME_KEY_PREFIX_VELOCITY_TEMPLATE), undefinedVelocityVariable)));
    // Try to get an S3 key prefix when the S3 key prefix velocity template contains an undefined variable.
    try {
        storageUnitService.getS3KeyPrefix(new BusinessObjectDataKey(NAMESPACE, BDEF_NAME, FORMAT_USAGE_CODE, FORMAT_FILE_TYPE_CODE, FORMAT_VERSION, PARTITION_VALUE, SUBPARTITION_VALUES, DATA_VERSION), testPartitionKey, STORAGE_NAME_2, false);
        fail("Should throw an MethodInvocationException when the S3 key prefix velocity template contains an undefined variable.");
    } catch (MethodInvocationException e) {
        assertEquals(String.format("Variable %s has not been set at %s[line 1, column 1]", undefinedVelocityVariable, configurationHelper.getProperty(ConfigurationValue.S3_ATTRIBUTE_NAME_KEY_PREFIX_VELOCITY_TEMPLATE)), e.getMessage());
    }
}
Also used : Attribute(org.finra.herd.model.api.xml.Attribute) SchemaColumn(org.finra.herd.model.api.xml.SchemaColumn) MethodInvocationException(org.apache.velocity.exception.MethodInvocationException) BusinessObjectDataKey(org.finra.herd.model.api.xml.BusinessObjectDataKey) Test(org.junit.Test)

Example 3 with MethodInvocationException

use of org.apache.velocity.exception.MethodInvocationException in project scoold by Erudika.

the class VelocityView method mergeTemplate.

/**
 * 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);
    }
}
Also used : NestedServletException(org.springframework.web.util.NestedServletException) MethodInvocationException(org.apache.velocity.exception.MethodInvocationException)

Example 4 with MethodInvocationException

use of org.apache.velocity.exception.MethodInvocationException in project openolat by klemens.

the class VelocityHelper method merge.

/**
 * @param template e.g. org/olat/demo/_content/index.html
 * @param c the context
 * @param theme the theme e.g. "accessibility" or "printing". may be null if the default theme ("") should be taken
 * @return String the rendered template
 */
private void merge(String template, Context c, Writer wOut, String theme) {
    try {
        Template vtemplate = null;
        if (isLogDebugEnabled())
            logDebug("Merging template::" + template + " for theme::" + theme, null);
        if (theme != null) {
            // try the theme first, if resource not found exception, fallback to normal resource.
            // e.g. try /_accessibility/index.html first, if not found, try /index.html.
            // this allows for themes to only provide the delta to the default templates
            // todo we could avoid those string operations, if the performance gain is measureable
            int latestSlash = template.lastIndexOf('/');
            StringBuilder sb = new StringBuilder(template.substring(0, latestSlash));
            sb.append("/_").append(theme).append("/").append(template.substring(latestSlash + 1));
            String themedTemplatePath = sb.toString();
            // check cache
            boolean notFound = resourcesNotFound.contains(themedTemplatePath);
            if (!notFound) {
                // never tried before -> try to load it
                if (!ve.resourceExists(themedTemplatePath)) {
                    // this will happen once for each theme when a resource does not exist in its themed variant but only in the default theme.
                    if (!Settings.isDebuging()) {
                        resourcesNotFound.add(themedTemplatePath);
                    }
                // for debugging, allow introduction of themed files without restarting the application
                } else {
                    // template exists -> load it
                    vtemplate = ve.getTemplate(themedTemplatePath, VelocityModule.getInputEncoding());
                }
            }
            // if not found, fallback to standard
            if (vtemplate == null) {
                vtemplate = ve.getTemplate(template, VelocityModule.getInputEncoding());
            }
        } else {
            // no theme, load the standard template
            vtemplate = ve.getTemplate(template, VelocityModule.getInputEncoding());
        }
        vtemplate.merge(c, wOut);
    } catch (MethodInvocationException me) {
        throw new OLATRuntimeException(VelocityHelper.class, "MethodInvocationException occured while merging template: methName:" + me.getMethodName() + ", refName:" + me.getReferenceName(), me.getWrappedThrowable());
    } catch (Exception e) {
        throw new OLATRuntimeException(VelocityHelper.class, "exception occured while merging template: " + e.getMessage(), e);
    }
}
Also used : OLATRuntimeException(org.olat.core.logging.OLATRuntimeException) MethodInvocationException(org.apache.velocity.exception.MethodInvocationException) AssertException(org.olat.core.logging.AssertException) MethodInvocationException(org.apache.velocity.exception.MethodInvocationException) OLATRuntimeException(org.olat.core.logging.OLATRuntimeException) Template(org.apache.velocity.Template)

Example 5 with MethodInvocationException

use of org.apache.velocity.exception.MethodInvocationException in project wcomponents by BorderTech.

the class VelocityInterceptor method paint.

/**
 * Renders the component using the velocity template which has been provided.
 *
 * @param renderContext the context for rendering.
 */
@Override
public void paint(final RenderContext renderContext) {
    if (!(renderContext instanceof WebXmlRenderContext)) {
        throw new SystemException("Unable to render to " + renderContext);
    }
    PrintWriter writer = ((WebXmlRenderContext) renderContext).getWriter();
    Template template = null;
    try {
        template = VelocityEngineFactory.getVelocityEngine().getTemplate(templateUrl);
    } catch (Exception ex) {
        String message = "Could not open velocity template \"" + templateUrl + "\" for \"" + this.getClass().getName() + "\"";
        LOG.error(message, ex);
        writer.println(message);
        return;
    }
    try {
        VelocityContext context = new VelocityContext();
        fillContext(context);
        template.merge(context, writer);
    } catch (ResourceNotFoundException rnfe) {
        LOG.error("Could not find template " + templateUrl, rnfe);
    } catch (ParseErrorException pee) {
        // syntax error : problem parsing the template
        LOG.error("Parse problems", pee);
    } catch (MethodInvocationException mie) {
        // something invoked in the template
        // threw an exception
        Throwable wrapped = mie.getWrappedThrowable();
        LOG.error("Problems with velocity", mie);
        if (wrapped != null) {
            LOG.error("Wrapped exception...", wrapped);
        }
    } catch (Exception e) {
        LOG.error("Problems with velocity", e);
    }
}
Also used : WebXmlRenderContext(com.github.bordertech.wcomponents.servlet.WebXmlRenderContext) SystemException(com.github.bordertech.wcomponents.util.SystemException) VelocityContext(org.apache.velocity.VelocityContext) ParseErrorException(org.apache.velocity.exception.ParseErrorException) MethodInvocationException(org.apache.velocity.exception.MethodInvocationException) ResourceNotFoundException(org.apache.velocity.exception.ResourceNotFoundException) ParseErrorException(org.apache.velocity.exception.ParseErrorException) SystemException(com.github.bordertech.wcomponents.util.SystemException) MethodInvocationException(org.apache.velocity.exception.MethodInvocationException) ResourceNotFoundException(org.apache.velocity.exception.ResourceNotFoundException) PrintWriter(java.io.PrintWriter) Template(org.apache.velocity.Template)

Aggregations

MethodInvocationException (org.apache.velocity.exception.MethodInvocationException)18 ParseErrorException (org.apache.velocity.exception.ParseErrorException)13 ResourceNotFoundException (org.apache.velocity.exception.ResourceNotFoundException)13 IOException (java.io.IOException)9 Template (org.apache.velocity.Template)8 VelocityContext (org.apache.velocity.VelocityContext)8 StringWriter (java.io.StringWriter)7 FileOutputStream (java.io.FileOutputStream)3 SystemException (com.github.bordertech.wcomponents.util.SystemException)2 File (java.io.File)2 FileWriter (java.io.FileWriter)2 OutputStreamWriter (java.io.OutputStreamWriter)2 PrintWriter (java.io.PrintWriter)2 Writer (java.io.Writer)2 DecimalFormat (java.text.DecimalFormat)2 Properties (java.util.Properties)2 MojoExecutionException (org.apache.maven.plugin.MojoExecutionException)2 NumberTool (org.apache.velocity.tools.generic.NumberTool)2 AbstractWComponent (com.github.bordertech.wcomponents.AbstractWComponent)1 WComponent (com.github.bordertech.wcomponents.WComponent)1