下面列出了怎么用org.apache.velocity.exception.ParseErrorException的API类实例代码及写法,或者点击链接到github查看源代码。
@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;
}
public VelocityTemplateParser(String templateString) throws ParseErrorException {
VelocityEngine engine = new VelocityEngine();
engine.setProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM_CLASS, "org.apache.velocity.runtime.log.Log4JLogChute");
engine.setProperty("runtime.log.logsystem.log4j.logger", LOG.getName());
engine.setProperty(Velocity.RESOURCE_LOADER, "string");
engine.addProperty("string.resource.loader.class", StringResourceLoader.class.getName());
engine.addProperty("string.resource.loader.repository.static", "false");
engine.addProperty("runtime.references.strict", "true");
engine.init();
StringResourceRepository resourceRepository = (StringResourceRepository) engine.getApplicationAttribute(StringResourceLoader.REPOSITORY_NAME_DEFAULT);
resourceRepository.putStringResource(TEMPLATE_NAME, templateString);
template = engine.getTemplate(TEMPLATE_NAME);
ASTprocess data = (ASTprocess) template.getData();
visitor = new ParserNodeVisitor();
data.jjtAccept(visitor, null);
}
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);
}
}
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;
}
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;
}
/**
* 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();
}
/**
* 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();
}
/**
* 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();
}
/**
* 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");
}
}
}
/**
* 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);
}
/**
* 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;
}
}
/**
* 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 ResourceNotFoundException
* @throws ParseErrorException
* @throws MethodInvocationException
* @since Velocity v1.1
*/
public boolean mergeTemplate( String templateName, String encoding,
Context context, Writer writer )
throws ResourceNotFoundException, ParseErrorException, MethodInvocationException
{
Template template = ri.getTemplate(templateName, encoding);
if ( template == null )
{
String msg = "VelocityEngine.mergeTemplate() was unable to load template '"
+ templateName + "'";
getLog().error(msg);
throw new ResourceNotFoundException(msg);
}
else
{
template.merge(context, writer);
return true;
}
}
/**
* @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
{
SpaceGobbling spaceGobbling = rsvc.getSpaceGobbling();
if (spaceGobbling == SpaceGobbling.NONE)
{
writer.write(prefix);
}
int i, k = jjtGetNumChildren();
for (i = 0; i < k; i++)
jjtGetChild(i).render(context, writer);
if (morePostfix.length() > 0 || spaceGobbling.compareTo(SpaceGobbling.LINES) < 0)
{
writer.write(postfix);
}
writer.write(morePostfix);
return true;
}
private void mergeTemplate(String name, String encoding, Map<String, Object> model, StringWriter writer)
throws ResourceNotFoundException, ParseErrorException, Exception {
VelocityContext velocityContext = new VelocityContext(model);
velocityContext.put("dateSymbol", new DateTool());
velocityContext.put("numberSymbol", new NumberTool());
velocityContext.put("mathSymbol", new MathTool());
Template template = engine().getTemplate(name, encoding);
template.merge(velocityContext, writer);
}
@Override
public boolean render(InternalContextAdapter context, Writer writer, Node node)
throws IOException, ResourceNotFoundException, ParseErrorException,
MethodInvocationException {
List placeList=(List) context.get("placeList");
if(placeList==null){
return true;
}
Object value=node.jjtGetChild(0).value(context);
placeList.add(value);
writer.write("?");
return true;
}
@Override
public boolean render(InternalContextAdapter context, Writer writer, Node node) throws IOException, ResourceNotFoundException, ParseErrorException, MethodInvocationException {
String clazz = (String) node.jjtGetChild(0).value(context);
if (context.containsKey(clazz)) {
String packagePath = context.get(clazz).toString();
packagePath = new StringBuilder("").append(packagePath).toString();
writer.write(packagePath);
return true;
}
return false;
}
@Override
public boolean render(InternalContextAdapter context, Writer writer, Node node) throws IOException, ResourceNotFoundException, ParseErrorException, MethodInvocationException {
String value = (String) node.jjtGetChild(0).value(context);
if (StringUtils.isBlank(value)) {
writer.write(value);
return true;
}
String result = value.replaceFirst(value.substring(0, 1), value.substring(0, 1).toLowerCase());
writer.write(result);
return true;
}
@Override
public boolean render(InternalContextAdapter context, Writer writer, Node node) throws IOException, ResourceNotFoundException, ParseErrorException, MethodInvocationException {
String clazz = (String) node.jjtGetChild(0).value(context);
if (context.containsKey(clazz)) {
String packagePath = context.get(clazz).toString();
packagePath = new StringBuilder("import ").append(packagePath).append(";\n").toString();
writer.write(packagePath);
return true;
}
return false;
}
@Override
public boolean render(InternalContextAdapter context, Writer writer, Node node) throws IOException, ResourceNotFoundException, ParseErrorException, MethodInvocationException {
String prefix = (String) node.jjtGetChild(0).value(context);
String str = (String) node.jjtGetChild(1).value(context);
String suffix = (String) node.jjtGetChild(2).value(context);
writer.write(String.valueOf(prefix + str + suffix));
return true;
}
@Override
public boolean render(InternalContextAdapter context, Writer writer, Node node) throws IOException, ResourceNotFoundException, ParseErrorException, MethodInvocationException {
String value = (String) node.jjtGetChild(0).value(context);
String result = value.replaceFirst(value.substring(0, 1), value.substring(0, 1).toUpperCase());
writer.write(result);
return true;
}
@Override
public boolean render(InternalContextAdapter context, Writer writer, Node node)
throws IOException, ResourceNotFoundException, ParseErrorException,
MethodInvocationException {
List placeList=(List) context.get("placeList");
if(placeList==null){
return true;
}
Object value=node.jjtGetChild(0).value(context);
placeList.add(value);
writer.write("?");
return true;
}
@Test(expected = ParseErrorException.class)
public void testParseInvalidVelocityTemplate() {
String templateString = "This alert ($category) was generated because $reason and $REASON from $source at $created_time #if() #fi";
VelocityTemplateParser parser = new VelocityTemplateParser(templateString);
Assert.assertEquals(5, parser.getReferenceNames().size());
Assert.assertArrayEquals(new String[]{"category", "reason", "REASON", "source", "created_time"}, parser.getReferenceNames().toArray());
}
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
if(enabled) {
try {
YuiCssCompressor compressor = new YuiCssCompressor();
compressor.setLineBreak(yuiCssLineBreak);
String result = compressor.compress(content.toString());
writer.write(result);
} catch (Exception e) {
writer.write(content.toString());
String msg = "Failed to compress content: "+content.toString();
log.error(msg, e);
throw new RuntimeException(msg, e);
}
} else {
writer.write(content.toString());
}
return true;
}
@Override
public final boolean render(InternalContextAdapter ica, Writer writer, Node node) throws IOException,
ResourceNotFoundException, ParseErrorException, MethodInvocationException {
Params p = getParams(ica, node);
if (p == null) {
return false;
} else {
return render(p, writer);
}
}
protected Params getParams(final InternalContextAdapter context, final Node node) throws IOException,
ResourceNotFoundException, ParseErrorException, MethodInvocationException {
final Params params = new Params();
final int nodes = node.jjtGetNumChildren();
for (int i = 0; i < nodes; i++) {
Node child = node.jjtGetChild(i);
if (child != null) {
if (!(child instanceof ASTBlock)) {
if (i == 0) {
params.setPrefix(String.valueOf(child.value(context)));
} else if (i == 1) {
params.setPrefixOverrides(String.valueOf(child.value(context)).toUpperCase(Locale.ENGLISH));
} else if (i == 2) {
params.setSuffix(String.valueOf(child.value(context)));
} else if (i == 3) {
params.setSuffixOverrides(String.valueOf(child.value(context)).toUpperCase(Locale.ENGLISH));
} else {
break;
}
} else {
StringWriter blockContent = new StringWriter();
child.render(context, blockContent);
if ("".equals(blockContent.toString().trim())) {
return null;
}
params.setBody(blockContent.toString().trim());
break;
}
}
}
return params;
}
/**
* Returns a markdown header string that should appear at the top of Stardoc's output, providing a
* summary for the input Starlark module.
*/
public String renderMarkdownHeader(ModuleInfo moduleInfo) throws IOException {
VelocityContext context = new VelocityContext();
context.put("util", new MarkdownUtil());
context.put("moduleDocstring", moduleInfo.getModuleDocstring());
StringWriter stringWriter = new StringWriter();
Reader reader = readerFromPath(headerTemplateFilename);
try {
velocityEngine.evaluate(context, stringWriter, headerTemplateFilename, reader);
} catch (ResourceNotFoundException | ParseErrorException | MethodInvocationException e) {
throw new IOException(e);
}
return stringWriter.toString();
}
private Set<String> prepareVelocityTemplate(String template)
throws PIPException {
VelocityContext vctx = new VelocityContext();
EventCartridge vec = new EventCartridge();
VelocityParameterReader reader = new VelocityParameterReader();
vec.addEventHandler(reader);
vec.attachToContext(vctx);
try {
Velocity.evaluate(vctx, new StringWriter(),
"LdapResolver", template);
}
catch (ParseErrorException pex) {
throw new PIPException(
"Velocity template preparation failed",pex);
}
catch (MethodInvocationException mix) {
throw new PIPException(
"Velocity template preparation failed",mix);
}
catch (ResourceNotFoundException rnfx) {
throw new PIPException(
"Velocity template preparation failed",rnfx);
}
if (this.logger.isTraceEnabled()) {
this.logger.trace("(" + id + ") " + template + " with parameters " + reader.parameters);
}
return reader.parameters;
}
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();
}
/**
* 获取并解析模版
* @param templateFile
* @return template
* @throws Exception
*/
private static Template buildTemplate(String templateFile) {
Template template = null;
try {
template = Velocity.getTemplate(templateFile);
} catch (ResourceNotFoundException rnfe) {
logger.error("buildTemplate error : cannot find template " + templateFile);
} catch (ParseErrorException pee) {
logger.error("buildTemplate error in template " + templateFile + ":" + pee);
} catch (Exception e) {
logger.error("buildTemplate error in template " + templateFile + ":" + e);
}
return template;
}
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);
}
}