Java org.apache.velocity.exception.MethodInvocationException 代码实例

・22 分钟阅读

以下是展示如何使用org.apache.velocity.exception.MethodInvocationException的最佳示例。 我们使用了代码质量辨别算法从开源项目中提取出了最佳的优秀示例。

实例 1


@Override
public Object eval(String src) throws ScriptException {
    if (m_ve == null) {
        throw new ScriptException("Velocity engine not initialized.");
    } else {
        Writer w = new StringWriter();
        try {
            if (m_ve.evaluate(c, w, "log", new StringReader(src))) {
                return w.toString();
            } else {
                throw new ScriptException("Velocity engine unexpected error.");
            }
        } catch (ParseErrorException e) {
            throw new ScriptException(e.getMessage(), e);
        } catch (MethodInvocationException e) {
            throw new ScriptException(e.getMessage(), e);
        } catch (Exception e) {
            throw new ScriptException(e.getMessage(), e);
        }
    }
}
 

实例 2


public void dispatch(String path, HttpServletRequest request,
                HttpServletResponse response) throws ServletException
{
        VelocityContext vcontext = new VelocityContext();
        // EventCartridge ec = new EventCartridge();
        // ec.addEventHandler(new ExcludeEscapeHtmlReference());
        // ec.attachToContext(vcontext);
        vcontext.put("session", request.getSession());
        vcontext.put("request", request);
        vcontext.put("requestScope", RequestScopeSuperBean.getFromRequest(request));
        vcontext.put("util", utilBean);
        try
        {
                String filePath = path + ".vm";
                response.setContentType("text/html");
                response.setCharacterEncoding("UTF-8");
                vengine.mergeTemplate(filePath, vcontext, response.getWriter());
        }
        catch (MethodInvocationException e)
        {
                Throwable cause = e.getWrappedThrowable();
                if (cause instanceof PermissionException)
                {
                        try
                        {
                                String filePath = "/WEB-INF/vm/permission.vm";
                                response.setContentType("text/html");
                                response.setCharacterEncoding("UTF-8");
                                vengine.mergeTemplate(filePath, vcontext, response.getWriter());
                        }
                        catch (Exception ex)
                        {
                                throw new ServletException(ex);
                        }
                }
                else
                {
                        throw new ServletException(e);
                }
        }
        catch (Exception e)
        {
                throw new ServletException(e);
        }
}
 

实例 3


public static void main(String[] args) {
        try {
                Velocity.init();
                VelocityContext context = new VelocityContext();
                Class<?> beanClazz = Class.forName(args[0]);
                Field[] fields = beanClazz.getDeclaredFields();
                context.put("allColumnsDb", getNames(fields, true));
                context.put("allColumnsCamel", getNames(fields, false));
                context.put("allTypesDb", getTypes(fields, true));
                context.put("allTypesExplicit", getTypes(fields, false));
                context.put("beanName", beanClazz.getSimpleName());
                Template template = null;
                template = Velocity.getTemplate(TEMPLATE_PATH);
                StringWriter sw = new StringWriter();
                template.merge(context, sw);
                System.out.println(sw.toString());
                File genFolder = new File("./gen");
                genFolder.mkdir();
                File dataAccessFile = new File("gen" + File.separator + beanClazz.getSimpleName() + "DataAccess.java");
                if (dataAccessFile.exists()) {
                        dataAccessFile.delete();
                }
                FileWriter fw = new FileWriter(dataAccessFile);
                fw.write(sw.toString());
                fw.close();
                sw.close();
        } catch (ResourceNotFoundException e) {
                System.out.println("Couldn't the template " + TEMPLATE_PATH + " " + e.toString());
        } catch (ParseErrorException e) {
                System.out.println("syntax error: problem parsing the template " + e.toString());
        } catch (MethodInvocationException e) {
                System.out.println("something invoked in the template " + e.toString());
        } catch (Exception e) {
                System.out.println("Unrecognized exception " + e.getMessage());
                e.printStackTrace();
        }
}
 

实例 4


public String generateSnmpGraph(Collection<Report> reports, String graphTemplate) {
    Velocity.init();
    VelocityContext context = new VelocityContext();
    context.put("reportsList", reports.iterator());
    context.put("reportsBody", reports.iterator());
    Template template = null;
    try {
        template = Velocity.getTemplate(graphTemplate);
    } catch (ResourceNotFoundException rnfe) {
        logger.debug("couldn't find the template:'{}'", rnfe.getMessage());
    } catch (ParseErrorException pee) {
        logger.debug("syntax error: problem parsing the template:'{}'", pee.getMessage());
    } catch (MethodInvocationException mie) {
        logger.debug("something invoked in the template threw an exception:'{}'", mie.getMessage());
    } catch (Exception e) {
        logger.debug("undefined exception:'{}'", e.getMessage());
    }
    StringWriter sw = new StringWriter();
    if (template != null) {
        template.merge(context, sw);
    }
    return sw.toString();
}
 

实例 5


public static void GenerationClasseJava(UMLClass cl) {
        Template template = null;
        VelocityContext context = new VelocityContext();
        StringWriter sw = new StringWriter();
        try {
                Velocity.init();
                context.put("class", cl );
                template = Velocity.getTemplate("TemplateJava.vm");
                template.merge( context, sw );
                FileWriter fw = new FileWriter(new File(cl.getIdentifier()+".java"));
                fw.write(sw.toString());
                fw.close();
        }
        catch( ResourceNotFoundException rnfe ){
                // couldn't find the template
        }
        catch( ParseErrorException pee ){
                // syntax error: problem parsing the template
        }
        catch( MethodInvocationException mie ){
                // something invoked in the template
                // threw an exception
        }
        catch( Exception e ){
                // Autre Exception
        }
}
 

实例 6


public void dispatch(String path, HttpServletRequest request,
                HttpServletResponse response) throws ServletException
{
        VelocityContext vcontext = new VelocityContext();
        // EventCartridge ec = new EventCartridge();
        // ec.addEventHandler(new ExcludeEscapeHtmlReference());
        // ec.attachToContext(vcontext);
        vcontext.put("session", request.getSession());
        vcontext.put("request", request);
        vcontext.put("requestScope", RequestScopeSuperBean.getFromRequest(request));
        vcontext.put("util", utilBean);
        try
        {
                String filePath = path + ".vm";
                response.setContentType("text/html");
                response.setCharacterEncoding("UTF-8");
                vengine.mergeTemplate(filePath, vcontext, response.getWriter());
        }
        catch (MethodInvocationException e)
        {
                Throwable cause = e.getWrappedThrowable();
                if (cause instanceof PermissionException)
                {
                        try
                        {
                                String filePath = "/WEB-INF/vm/permission.vm";
                                response.setContentType("text/html");
                                response.setCharacterEncoding("UTF-8");
                                vengine.mergeTemplate(filePath, vcontext, response.getWriter());
                        }
                        catch (Exception ex)
                        {
                                throw new ServletException(ex);
                        }
                }
                else
                {
                        throw new ServletException(e);
                }
        }
        catch (Exception e)
        {
                throw new ServletException(e);
        }
}
 

实例 7


@Override
public Object eval(String src) throws ScriptException {
    if (m_ve == null) {
        throw new ScriptException("Velocity engine not initialized.");
    } else {
        Writer w = new StringWriter();
        try {
            if (m_ve.evaluate(c, w, "log", new StringReader(src))) {
                return w.toString();
            } else {
                throw new ScriptException("Velocity engine unexpected error.");
            }
        } catch (ParseErrorException e) {
            throw new ScriptException(e.getMessage(), e);
        } catch (MethodInvocationException e) {
            throw new ScriptException(e.getMessage(), e);
        } catch (Exception e) {
            throw new ScriptException(e.getMessage(), e);
        }
    }
}
 

实例 8


@Override
public void handle(HttpRequest  request,
                   HttpResponse response,
                   HttpContext  context) throws HttpException, IOException {
    String view = (String)context.getAttribute(ATTR_VIEW);
    if (view == null) {
        return;
    }
    view = getViewPath(request.getRequestLine().getUri(), view);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    Writer out = new OutputStreamWriter(baos);
    try {
        Template t = engine.getTemplate(view);
        t.merge(buildContext(request, (HttpSessionContext)context), out); out.flush();
    } catch (ResourceNotFoundException e) {
        response.setStatusLine(HttpVersion.HTTP_1_1, HttpStatus.SC_NOT_FOUND, "View " + view + " not found.");
        return;
    } catch (ParseErrorException e) {
        throw new HttpException("Parse error evaluating " + view + ": " + e, e);
    } catch (MethodInvocationException e) {
        throw new HttpException("Method invocation error evaluating " + view + ": " + e, e);
    }
    BasicHttpEntity body = (BasicHttpEntity)response.getEntity();
    body.setContentLength(baos.size());
    body.setContent(new ByteArrayInputStream(baos.toByteArray()));
    if ((body.getContentType() == null) || StringUtils.isBlank(body.getContentType().getValue())) {
        body.setContentType(ContentType.TEXT_HTML.getMimeType());
    }
}
 

实例 9


public Object eval(String src) throws ScriptException {
    if (m_ve == null) {
        throw new ScriptException("Velocity engine not initialized.");
    } else {
        Writer w = new StringWriter();
        try {
            if (m_ve.evaluate(c, w, "log", new StringReader(src))) {
                return w.toString();
            } else {
                throw new ScriptException("Velocity engine unexpected error.");
            }
        } catch (ParseErrorException e) {
            throw new ScriptException(e.getMessage(), e);
        } catch (MethodInvocationException e) {
            throw new ScriptException(e.getMessage(), e);
        } catch (Exception e) {
            throw new ScriptException(e.getMessage(), e);
        }
    }
}
 

实例 10


@Override
public Object eval(String src) throws ScriptException {
    if (m_ve == null) {
        throw new ScriptException("Velocity engine not initialized.");
    } else {
        Writer w = new StringWriter();
        try {
            if (m_ve.evaluate(c, w, "log", new StringReader(src))) {
                return w.toString();
            } else {
                throw new ScriptException("Velocity engine unexpected error.");
            }
        } catch (ParseErrorException e) {
            throw new ScriptException(e.getMessage(), e);
        } catch (MethodInvocationException e) {
            throw new ScriptException(e.getMessage(), e);
        } catch (Exception e) {
            throw new ScriptException(e.getMessage(), e);
        }
    }
}
 

实例 11


public String merge(Map<String, Object> context) {
    StringWriter writer = new StringWriter();
    velocityContext = new VelocityContext(context);
    try {
        velocityEngine.evaluate(velocityContext, writer, "mailGenerated", new InputStreamReader(inputStream));
    }
    catch (ResourceNotFoundException e) {
        throw new TemplatingException("Unable to find template", e);
    }
    catch (ParseErrorException e) {
        throw new TemplatingException("Unable to find template", e);
    }
    catch (MethodInvocationException e) {
        throw new TemplatingException("Error processing method referenced in context", e);
    }
    return writer.toString();
}
 

实例 12


/**
 * Used to put Velocity macro arguments into this context. 
 * 
 * @param context rendering context
 * @param macroArgumentName name of the macro argument that we received
 * @param literalMacroArgumentName ".literal.$"+macroArgumentName
 * @param argumentValue actual value of the macro argument
 * 
 * @throws MethodInvocationException
 */
public void addVMProxyArg(InternalContextAdapter context,
                          String macroArgumentName,
                          String literalMacroArgumentName,
                          Node argumentValue) throws MethodInvocationException
{
    if (isConstant(argumentValue))
    {
        localcontext.put(macroArgumentName, argumentValue.value(context));
    }
    else
    {
        vmproxyhash.put(macroArgumentName, argumentValue);
        localcontext.put(literalMacroArgumentName, argumentValue);
    }
}
 

实例 13


@Override
protected Params getParams(InternalContextAdapter context, Node node) throws IOException, ResourceNotFoundException, ParseErrorException, MethodInvocationException {
  final Params params = new Params();
  params.setPrefix("WHERE");
  params.setPrefixOverrides("AND |OR |ANDn|ORn|ANDr|ORr");
  if (node.jjtGetNumChildren() == 1) {
    final Node child = node.jjtGetChild(0);
    if (child instanceof ASTBlock) {
      StringWriter blockContent = new StringWriter();
      child.render(context, blockContent);
      params.setBody(blockContent.toString().trim());
      return params;
    }
  }
  return null;
}
 

实例 14


@Override
public boolean render(final InternalContextAdapter context,
                      final Writer writer,
                      final Node node)
        throws IOException, ResourceNotFoundException,
               ParseErrorException, MethodInvocationException {
    final List<Object> chainOfBlock = getBlockChain(context, node);
    if (chainOfBlock == null) return false;
    if (writer instanceof ApplyWriter) { // inside apply derective
        if (chainOfBlock.contains(BASEBLOCK_RENDERING_POSITION_MARKER)) {
            final Object blockObject = parseBlock(context, node.jjtGetChild(1));
            if (blockObject == null) return false;
            chainOfBlock.add(chainOfBlock.indexOf(BASEBLOCK_RENDERING_POSITION_MARKER) + 1,
                             blockObject);
        }
        return true;
    }
    else {
        return helper_.warn("found outside of #apply");
    }
}
 

实例 15


@Override
public String format( final String templateBasepath, String templateName, final Map<String, Object> context )
    throws TemplateException
{
    init();
    if ( templateName == null )
    {
        templateName = DEFAULT_TEMPLATE_NAME;
    }
    else if ( !templateName.endsWith( ".vm" ) )
    {
        templateName += ".vm";
    }
    final String templatePath = joinPath( '/', templateBasepath, templateName );
    final VelocityContext ctx = new VelocityContext( new HashMap<String, Object>( context ) );
    final StringWriter writer = new StringWriter();
    final String template = readTemplate( templatePath );
    if ( template == null )
    {
        throw new TemplateException( "Template not found: %s", templateName );
    }
    try
    {
        velocity.evaluate( ctx, writer, templateName, template );
    }
    catch ( final ResourceNotFoundException e )
    {
        throw new TemplateException(
                                     "Failed to render capture session using Velocity template.nTemplate: %snReason: %s",
                                     e, templatePath, e.getMessage() );
    }
    catch ( final ParseErrorException e )
    {
        throw new TemplateException(
                                     "Failed to render capture session using Velocity template.nTemplate: %snReason: %s",
                                     e, templatePath, e.getMessage() );
    }
    catch ( final MethodInvocationException e )
    {
        throw new TemplateException(
                                     "Failed to render capture session using Velocity template.nTemplate: %snReason: %s",
                                     e, templatePath, e.getMessage() );
    }
    catch ( final IOException e )
    {
        throw new TemplateException(
                                     "Failed to render capture session using Velocity template.nTemplate: %snReason: %s",
                                     e, templatePath, e.getMessage() );
    }
    logger.info( "rendered output:nn" + writer.toString() + "nn" );
    return writer.toString();
}
 
讨论
淘淘あ西西 profile image