本文整理匯總了Java中org.apache.velocity.app.Velocity類的典型用法代碼示例。如果您正苦於以下問題:Java Velocity類的具體用法?Java Velocity怎麽用?Java Velocity使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
Velocity類屬於org.apache.velocity.app包,在下文中一共展示了Velocity類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: generate
import org.apache.velocity.app.Velocity; //導入依賴的package包/類
/**
* 根據模板生成文件
* @param inputVmFilePath 模板路徑
* @param outputFilePath 輸出文件路徑
* @param context
* @throws Exception
*/
public static void generate(String inputVmFilePath, String outputFilePath, VelocityContext context) throws Exception {
try {
Properties properties = new Properties();
properties.setProperty(VelocityEngine.FILE_RESOURCE_LOADER_PATH, getPath(inputVmFilePath));
Velocity.init(properties);
//VelocityEngine engine = new VelocityEngine();
Template template = Velocity.getTemplate(getFile(inputVmFilePath), "utf-8");
File outputFile = new File(outputFilePath);
FileWriterWithEncoding writer = new FileWriterWithEncoding(outputFile, "utf-8");
template.merge(context, writer);
writer.close();
} catch (Exception ex) {
throw ex;
}
}
示例2: VelocityDefaultConfigurationFactory
import org.apache.velocity.app.Velocity; //導入依賴的package包/類
@Inject
public VelocityDefaultConfigurationFactory(@Optional final ServletContext servletContext) {
String loader = "class";
Velocity.setProperty("class.resource.loader.class", ClasspathResourceLoader.class.getName());
Velocity.setProperty(RuntimeConstants.FILE_RESOURCE_LOADER_CACHE, "true");
if (servletContext != null) {
Velocity.setProperty("webapp.resource.loader.class", WebappResourceLoader.class.getName());
Velocity.setProperty("webapp.resource.loader.path", "/");
Velocity.setApplicationAttribute("javax.servlet.ServletContext", servletContext);
loader += ",webapp";
}
Velocity.setProperty(RuntimeConstants.RESOURCE_LOADER, loader);
configuration = new Configuration();
}
示例3: usage1
import org.apache.velocity.app.Velocity; //導入依賴的package包/類
public void usage1(String inputFile) throws FileNotFoundException {
Velocity.init();
VelocityContext context = new VelocityContext();
context.put("author", "Elliot A.");
context.put("address", "217 E Broadway");
context.put("phone", "555-1337");
FileInputStream file = new FileInputStream(inputFile);
//Evaluate
StringWriter swOut = new StringWriter();
Velocity.evaluate(context, swOut, "test", file);
String result = swOut.getBuffer().toString();
System.out.println(result);
}
示例4: createTable
import org.apache.velocity.app.Velocity; //導入依賴的package包/類
@Override
public String createTable(Grammar grammar) {
Velocity.setProperty(RuntimeConstants.OUTPUT_ENCODING, "UTF-8");
Velocity.setProperty(RuntimeConstants.INPUT_ENCODING, "UTF-8");
Velocity.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
Velocity.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
Velocity.init();
VelocityContext context = new VelocityContext();
context.put("grammar", grammar);
context.put("nonterminalSymbols", grammar.getLhsSymbols());
Template template = Velocity.getTemplate("/grammartools/PredictiveParsingTable.velo");
StringWriter stringWriter = new StringWriter();
template.merge(context, stringWriter);
return stringWriter.toString().replaceAll("\n", "");
}
示例5: outputCode
import org.apache.velocity.app.Velocity; //導入依賴的package包/類
public void outputCode(String codePath, String templatePath) throws IOException {
VelocityContext context = new VelocityContext();
context.put("cModule", cModule);
Template template = null;
try {
template = Velocity.getTemplate(templatePath, TEMPLATE_ENCODING);
} catch (ResourceNotFoundException e) {
throw e;
}
File file = new File(codePath);
logger.info("Generating {} ({})", file.getName(), templatePath);
PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), OUTPUT_ENCODING)));
template.merge(context, pw);
pw.close();
}
示例6: getTemplate
import org.apache.velocity.app.Velocity; //導入依賴的package包/類
/**
* Gets the template by viewname, the viewname is relative path
*
* @param viewname
* the relative view path name
* @param allowEmpty
* if not presented, allow using a empty
* @return Template
* @throws IOException
*/
private Template getTemplate(File f) throws IOException {
String fullname = f.getCanonicalPath();
T t = cache.get(fullname);
if (t == null || t.last != f.lastModified()) {
/**
* get the template from the top
*/
Template t1 = Velocity.getTemplate(fullname, "UTF-8");
t = T.create(t1, f.lastModified());
cache.put(fullname, t);
}
return t == null ? null : t.template;
}
示例7: showTasks
import org.apache.velocity.app.Velocity; //導入依賴的package包/類
private void showTasks(HttpServletRequest request, HttpServletResponse response, Collection<TaskRecord> tasks, String title, boolean showDbStats)
throws IOException {
if ("json".equals(request.getParameter("format"))) {
response.setContentType("text/plain");
} else {
response.setContentType("text/html");
}
int offset = getOffset(request);
int length = getLength(request);
// Create Velocity context
VelocityContext context = new VelocityContext();
context.put("tasks", tasks);
context.put("title", title);
context.put("reportStore", metadata);
context.put("request", request);
context.put("offset", offset);
context.put("length", length);
context.put("lastResultNum", offset + length - 1);
context.put("prevOffset", Math.max(0, offset - length));
context.put("nextOffset", offset + length);
context.put("showStats", showDbStats);
context.put("JSON_DATE_FORMAT", JSON_DATE_FORMAT);
context.put("HTML_DATE_FORMAT", HTML_DATE_FORMAT);
context.put("PAGE_LENGTH", PAGE_LENGTH);
// Return Velocity results
try {
Velocity.mergeTemplate("tasks.vm", "UTF-8", context, response.getWriter());
response.setStatus(HttpServletResponse.SC_OK);
} catch (Exception e) {
LOG.warn("Failed to display tasks.vm", e);
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Failed to display tasks.vm");
}
}
示例8: VelocityViewProcessor
import org.apache.velocity.app.Velocity; //導入依賴的package包/類
@Inject
public VelocityViewProcessor(final javax.ws.rs.core.Configuration config, final ServiceLocator serviceLocator,
@Optional final ServletContext servletContext) {
super(config, servletContext, "velocity", "vm");
this.factory = getTemplateObjectFactory(serviceLocator, VelocityConfigurationFactory.class,
new Value<VelocityConfigurationFactory>() {
@Override
public VelocityConfigurationFactory get() {
Configuration configuration = getTemplateObjectFactory(serviceLocator, Configuration.class,
Values.<Configuration>empty());
if (configuration == null) {
return new VelocityDefaultConfigurationFactory(servletContext);
} else {
return new VelocitySuppliedConfigurationFactory(configuration);
}
}
});
Velocity.init();
}
示例9: parseTemplateAndRunExpect
import org.apache.velocity.app.Velocity; //導入依賴的package包/類
protected void parseTemplateAndRunExpect(String expectTemplateName, Map<String, String> contextVars) throws IOException, InterruptedException {
VelocityContext context = new VelocityContext();
for (Map.Entry<String, String> ent : contextVars.entrySet()) {
context.put(ent.getKey(), ent.getValue());
}
Template template = Velocity.getTemplate(expectTemplateName);
String inputPath = EXPECT_DIR + File.separator + expectTemplateName;
String outputPath = inputPath.substring(0, inputPath.length() - 3);
Writer output = new FileWriter(outputPath);
template.merge(context, output);
output.close();
expect(ZIPFILE_EXTRACTED, outputPath);
}
示例10: __doViewInit
import org.apache.velocity.app.Velocity; //導入依賴的package包/類
@Override
protected void __doViewInit(IWebMvc owner) {
super.__doViewInit(owner);
// 初始化Velocity模板引擎配置
if (!__inited) {
__velocityConfig.setProperty(Velocity.ENCODING_DEFAULT, owner.getModuleCfg().getDefaultCharsetEncoding());
__velocityConfig.setProperty(Velocity.INPUT_ENCODING, owner.getModuleCfg().getDefaultCharsetEncoding());
__velocityConfig.setProperty(Velocity.OUTPUT_ENCODING, owner.getModuleCfg().getDefaultCharsetEncoding());
//
if (__baseViewPath.startsWith("/WEB-INF")) {
__velocityConfig.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH, new File(RuntimeUtils.getRootPath(), StringUtils.substringAfter(__baseViewPath, "/WEB-INF/")).getPath());
} else {
__velocityConfig.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH, __baseViewPath);
}
//
Velocity.init(__velocityConfig);
//
__inited = true;
}
}
示例11: prepareVelocityTemplate
import org.apache.velocity.app.Velocity; //導入依賴的package包/類
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;
}
示例12: evaluateVelocityTemplate
import org.apache.velocity.app.Velocity; //導入依賴的package包/類
private String evaluateVelocityTemplate(String template,
final Map<String, PIPRequest> templateParameters,
final PIPFinder pipFinder)
throws PIPException {
StringWriter out = new StringWriter();
VelocityContext vctx = new VelocityContext();
EventCartridge vec = new EventCartridge();
VelocityParameterWriter writer = new VelocityParameterWriter(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();
}
示例13: doMerge
import org.apache.velocity.app.Velocity; //導入依賴的package包/類
public static String doMerge(String strToMerge, Map map) {
if (strToMerge == null)
return null;
try {
// ask Velocity to evaluate it.
Velocity.init();
StringWriter w = new StringWriter();
VelocityContext context = new VelocityContext(map);
Velocity.evaluate(context, w, "logTag", strToMerge);
return w.getBuffer().toString();
} catch (Exception e) {
return null;
}
}
示例14: evaluate
import org.apache.velocity.app.Velocity; //導入依賴的package包/類
/**
* Wrapper for {@link Velocity#evaluate(org.apache.velocity.context.Context, java.io.Writer, String, java.io.InputStream)}
*
* @param templateReader A {@link Reader} of a Velocity template.
* @param variables Variables to add to context
* @param logTag The log tag
*
* @return {@link String} result of evaluation
*/
public String evaluate(Reader templateReader, Map<String, Object> variables, String logTag)
{
VelocityContext velocityContext = new VelocityContext(variables);
StringWriter writer = new StringWriter();
if (!Velocity.evaluate(velocityContext, writer, logTag, templateReader))
{
// Although the Velocity.evaluate method's Javadoc states that it will return false to indicate a failure when the template couldn't be
// processed and to see the Velocity log messages for more details, upon examining the method's implementation, it doesn't look like
// it will ever return false. Instead, other RuntimeExceptions will be thrown (e.g. ParseErrorException).
// Nonetheless, we'll leave this checking here to honor the method's contract in case the implementation changes in the future.
// Having said that, there will be no way to JUnit test this flow.
throw new IllegalStateException("Error evaluating velocity template. See velocity log message for more details.");
}
return writer.toString();
}
示例15: start
import org.apache.velocity.app.Velocity; //導入依賴的package包/類
/**
* Simply initialize the Velocity engine
*/
@PostConstruct
public void start() throws Exception
{
try
{
Velocity.setProperty(Velocity.RESOURCE_LOADER, "cp");
Velocity.setProperty("cp.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
Velocity.setProperty("cp.resource.loader.cache", "true");
Velocity.setProperty("cp.resource.loader.modificationCheckInterval ", "0");
Velocity.setProperty("input.encoding", "UTF-8");
Velocity.setProperty("output.encoding", "UTF-8");
// Very busy servers should increase this value. Default: 20
// Velocity.setProperty("velocity.pool.size", "20");
Velocity.setProperty("runtime.log.logsystem.class", "org.apache.velocity.runtime.log.JdkLogChute");
Velocity.init();
log.log(Level.FINE,"Velocity initialized!");
}
catch (Exception ex)
{
log.log(Level.SEVERE,"Unable to initialize Velocity", ex);
throw new RuntimeException(ex);
}
}