org.apache.velocity.app.Velocity Java Examples

The following examples show how to use org.apache.velocity.app.Velocity. 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: Test2.java    From java-course-ee with MIT License 6 votes vote down vote up
public Test2() throws Exception {
    //init
    Velocity.init("Velocity/GS_Velocity_1/src/main/java/velocity.properties");
    // get Template
    Template template = Velocity.getTemplate("Test2.vm");
    // getContext
    Context context = new VelocityContext();

    String name = "Vova";

    context.put("name", name);
    // get Writer
    Writer writer = new StringWriter();
    // merge
    template.merge(context, writer);

    System.out.println(writer.toString());
}
 
Example #2
Source File: StringResourceLoaderRepositoryTestCase.java    From velocity-engine with Apache License 2.0 6 votes vote down vote up
public void setUp() throws Exception
{
    Velocity.reset();
    Velocity.setProperty(Velocity.RESOURCE_LOADERS, "string");
    Velocity.addProperty("string.resource.loader.class", StringResourceLoader.class.getName());
    Velocity.addProperty("string.resource.loader.modificationCheckInterval", "1");
    Velocity.setProperty(Velocity.RUNTIME_LOG_INSTANCE, new TestLogger());
    Velocity.init();

    StringResourceRepository repo = getRepo(null, null);
    repo.putStringResource("foo", "This is $foo");
    repo.putStringResource("bar", "This is $bar");

    context = new VelocityContext();
    context.put("foo", "wonderful!");
    context.put("bar", "horrible!");
    context.put("woogie", "a woogie");
}
 
Example #3
Source File: RenderTool.java    From velocity-tools with Apache License 2.0 6 votes vote down vote up
protected String internalEval(Context ctx, String vtl) throws Exception
{
    if (vtl == null)
    {
        return null;
    }
    StringWriter sw = new StringWriter();
    boolean success;
    if (engine == null)
    {
        success = Velocity.evaluate(ctx, sw, "RenderTool.eval()", vtl);
    }
    else
    {
        success = engine.evaluate(ctx, sw, "RenderTool.eval()", vtl);
    }
    if (success)
    {
        return sw.toString();
    }
    /* or would it be preferable to return the original? */
    return null;
}
 
Example #4
Source File: VelocityUtil.java    From sofa-acts with Apache License 2.0 6 votes vote down vote up
/**
 * Render text
 * 
 * @param context
 * @param template
 * @return
 */
public static synchronized String evaluateString(Map<String, Object> context, String template) {
    Writer writer = new StringWriter();
    try {
        VelocityContext velocityContext = new VelocityContext(context);

        addExtendProperties(velocityContext);

        Velocity.evaluate(velocityContext, writer, StringUtils.EMPTY, template);
        return writer.toString();
    } catch (Exception e) {
        throw new ActsException("velocity evaluate error[template=" + template + "]", e);
    } finally {
        IOUtils.closeQuietly(writer);
    }
}
 
Example #5
Source File: VelocityInitializer.java    From NutzSite with Apache License 2.0 6 votes vote down vote up
/**
 * 初始化vm方法
 */
public static void initVelocity()
{
    Properties p = new Properties();
    try
    {
        // 加载classpath目录下的vm文件
        p.setProperty("file.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
        // 定义字符集
        p.setProperty(Velocity.ENCODING_DEFAULT, Globals.UTF8);
        p.setProperty(Velocity.OUTPUT_ENCODING, Globals.UTF8);
        // 初始化Velocity引擎,指定配置Properties
        Velocity.init(p);
    }
    catch (Exception e)
    {
        throw new RuntimeException(e);
    }
}
 
Example #6
Source File: ResourceLoaderInstanceTestCase.java    From velocity-engine with Apache License 2.0 6 votes vote down vote up
public void setUp()
        throws Exception
{

    ResourceLoader rl = new FileResourceLoader();

    // pass in an instance to Velocity
    Velocity.reset();
    Velocity.setProperty( "resource.loader", "testrl" );
    Velocity.setProperty( "testrl.resource.loader.instance", rl );
    Velocity.setProperty( "testrl.resource.loader.path", FILE_RESOURCE_LOADER_PATH );

    // actual instance of logger
    logger.on();
    Velocity.setProperty(RuntimeConstants.RUNTIME_LOG_INSTANCE, logger);
    Velocity.setProperty("runtime.log.logsystem.test.level", "debug");

    Velocity.init();
}
 
Example #7
Source File: VelocityInitializer.java    From ruoyiplus with MIT License 6 votes vote down vote up
/**
 * 初始化vm方法
 */
public static void initVelocity()
{
    Properties p = new Properties();
    try
    {
        // 加载classpath目录下的vm文件
        p.setProperty("file.resource.loader.class",
                "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
        // 定义字符集
        p.setProperty(Velocity.ENCODING_DEFAULT, Constants.UTF8);
        p.setProperty(Velocity.OUTPUT_ENCODING, Constants.UTF8);
        // 初始化Velocity引擎,指定配置Properties
        Velocity.init(p);
    }
    catch (Exception e)
    {
        throw new RuntimeException(e);
    }
}
 
Example #8
Source File: Test1.java    From java-course-ee with MIT License 6 votes vote down vote up
public Test1() throws Exception {

        //init
        Velocity.init("Velocity/GS_Velocity_1/src/main/java/velocity.properties");
        // get Template
        Template template = Velocity.getTemplate("Test1.vm");
        // getContext
        Context context = new VelocityContext();
        // get Writer
        Writer writer = new StringWriter();
        // merge
        template.merge(context, writer);

        System.out.println(writer.toString());

    }
 
Example #9
Source File: AbstractTitanAssemblyIT.java    From titan1withtp3.1 with Apache License 2.0 6 votes vote down vote up
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);
}
 
Example #10
Source File: BaseTestCase.java    From velocity-engine with Apache License 2.0 6 votes vote down vote up
protected void info(String msg, Throwable t)
{
    if (DEBUG)
    {
        try
        {
            if (engine == null)
            {
                Velocity.getLog().info(msg, t);
            }
            else
            {
                engine.getLog().info(msg, t);
            }
        }
        catch (Throwable t2)
        {
            System.out.println("Failed to log: "+msg+(t!=null?" - "+t: ""));
            System.out.println("Cause: "+t2);
            t2.printStackTrace();
        }
    }
}
 
Example #11
Source File: VelocityUsage.java    From Android_Code_Arbiter with GNU Lesser General Public License v3.0 6 votes vote down vote up
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);
}
 
Example #12
Source File: ParseWithMacroLibsTestCase.java    From velocity-engine with Apache License 2.0 6 votes vote down vote up
/**
 * Return and initialize engine
 * @return
 */
private VelocityEngine createEngine(boolean cache, boolean local)
throws Exception
{
    VelocityEngine ve = new VelocityEngine();
    ve.setProperty( Velocity.VM_PERM_INLINE_LOCAL, Boolean.TRUE);
    ve.setProperty("velocimacro.permissions.allow.inline.to.replace.global",
        local);
    ve.setProperty("file.resource.loader.cache", cache);
    ve.setProperty(
            Velocity.RUNTIME_LOG_INSTANCE, new TestLogger());
    ve.setProperty(RuntimeConstants.RESOURCE_LOADERS, "file");
    ve.setProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH,
            TEST_COMPARE_DIR + "/parsemacros");
    ve.init();

    return ve;
}
 
Example #13
Source File: VelocityConfiguration.java    From DCMonitor with MIT License 6 votes vote down vote up
@Bean
VelocityViewResolver velocityViewResolver() {
  VelocityViewResolver resolver = new VelocityViewResolver();
  resolver.setSuffix(this.environment.getProperty("suffix", ".vm"));
  resolver.setPrefix(this.environment.getProperty("prefix", "/public/"));
  // Needs to come before any fallback resolver (e.g. a
  // InternalResourceViewResolver)
  resolver.setOrder(Ordered.LOWEST_PRECEDENCE - 20);
  Properties p = new Properties();
  p.put(Velocity.FILE_RESOURCE_LOADER_PATH, "/public/");
  p.put("input.encoding", "utf-8");
  p.put("output.encoding", "utf-8");
  resolver.setAttributes(p);
  resolver.setContentType("text/html;charset=utf-8");
  return resolver;
}
 
Example #14
Source File: VelocityTemplateParser.java    From eagle with Apache License 2.0 6 votes vote down vote up
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);
}
 
Example #15
Source File: VelocityGenerator.java    From cxf with Apache License 2.0 6 votes vote down vote up
private static synchronized void initVelocity(boolean log) throws ToolException {
        if (initialized) {
            return;
        }
        initialized = true;
        try {
            Properties props = new Properties();
            String clzName = "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader";
            props.put("resource.loaders", "class");
            props.put("resource.loader.class.class", clzName);
            props.put("runtime.log", getVelocityLogFile("velocity.log"));
//            if (!log) {
//                props.put(VelocityEngine.RUNTIME_LOG_INSTANCE,
//                          "org.apache.velocity.runtime.log.NullLogSystem");
//            }
            Velocity.init(props);
        } catch (Exception e) {
            Message msg = new Message("FAIL_TO_INITIALIZE_VELOCITY_ENGINE", LOG);
            LOG.log(Level.SEVERE, msg.toString());
            throw new ToolException(msg, e);
        }
    }
 
Example #16
Source File: MailUtil.java    From springboot-learn with MIT License 6 votes vote down vote up
/**
 * 获取velocity邮件模板内容
 *
 * @param map 模板中需替换的参数内容
 * @return
 */
public static String getTemplateText(String templatePath, String charset, Map<String, Object> map) {
    String templateText;
    // 设置velocity资源加载器
    Properties prop = new Properties();
    prop.put("file.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
    Velocity.init(prop);
    VelocityContext context = new VelocityContext(map);
    // 渲染模板
    StringWriter sw = new StringWriter();
    Template template = Velocity.getTemplate(templatePath, charset);
    template.merge(context, sw);
    try {
        templateText = sw.toString();
        sw.close();
    } catch (IOException e) {
        e.printStackTrace();
        throw new RuntimeException("模板渲染失败");
    }
    return templateText;
}
 
Example #17
Source File: VelocityUtil.java    From feiqu-opensource with Apache License 2.0 6 votes vote down vote up
/**
 * 根据模板生成文件
 * @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();
		String path = getPath(inputVmFilePath);
		properties.setProperty(VelocityEngine.FILE_RESOURCE_LOADER_PATH, path);
		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;
	}
}
 
Example #18
Source File: AbstractPOJOGenMojo.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
protected void parseObj(
    final File base,
    final boolean append,
    final String pkg,
    final String name,
    final String out,
    final Map<String, Object> objs)
    throws MojoExecutionException {

  final VelocityContext ctx = newContext();
  ctx.put("package", pkg);

  if (objs != null) {
    for (Map.Entry<String, Object> obj : objs.entrySet()) {
      if (StringUtils.isNotBlank(obj.getKey()) && obj.getValue() != null) {
        ctx.put(obj.getKey(), obj.getValue());
      }
    }
  }

  final Template template = Velocity.getTemplate(name + ".vm");
  writeFile(out, base, ctx, template, append);
}
 
Example #19
Source File: Container.java    From tomee with Apache License 2.0 6 votes vote down vote up
private void copyTemplateTo(final File targetDir, final String filename) throws Exception {
    final File file = new File(targetDir, filename);
    if (file.exists()) {
        return;
    }

    // don't break apps using Velocity facade
    final VelocityEngine engine = new VelocityEngine();
    engine.setProperty(Velocity.RUNTIME_LOG_LOGSYSTEM, new NullLogChute());
    engine.setProperty(Velocity.RESOURCE_LOADER, "class");
    engine.setProperty("class.resource.loader.description", "Velocity Classpath Resource Loader");
    engine.setProperty("class.resource.loader.class", ClasspathResourceLoader.class.getName());
    engine.init();
    final Template template = engine.getTemplate("/org/apache/tomee/configs/" + filename);
    final VelocityContext context = new VelocityContext();
    context.put("tomcatHttpPort", Integer.toString(configuration.getHttpPort()));
    context.put("tomcatShutdownPort", Integer.toString(configuration.getStopPort()));
    final Writer writer = new FileWriter(file);
    template.merge(context, writer);
    writer.flush();
    writer.close();
}
 
Example #20
Source File: VelocityClassLoaderTest.java    From RetroFacebook with Apache License 2.0 5 votes vote down vote up
/**
 * Make a different ClassLoader that loads the same URLs as this one, and use it to compile
 * an {@code @RetroFacebook} class. If Velocity loads its managers using the context class loader,
 * and that loader is still the original one that loaded this test, then it will find the
 * original copy of the Velocity classes rather than the one from the new loader, and fail.
 *
 * <p>This test assumes that the test class was loaded by a URLClassLoader and that that loader's
 * URLs also include the Velocity classes.
 */
public void testClassLoaderHack() throws Exception {
  URLClassLoader myLoader = (URLClassLoader) getClass().getClassLoader();
  URLClassLoader newLoader = new URLClassLoader(myLoader.getURLs(), myLoader.getParent());
  String velocityClassName = Velocity.class.getName();
  Class<?> myVelocity = myLoader.loadClass(velocityClassName);
  Class<?> newVelocity = newLoader.loadClass(velocityClassName);
  assertThat(myVelocity).isNotEqualTo(newVelocity);
  Runnable test = (Runnable) newLoader.loadClass(RunInClassLoader.class.getName()).newInstance();
  assertThat(test.getClass()).isNotEqualTo(RunInClassLoader.class);
  test.run();
}
 
Example #21
Source File: PlayerScriptProcessor.java    From jsflight with Apache License 2.0 5 votes vote down vote up
public JSONObject runStepTemplating(UserScenario scenario, JSONObject step)
{
    VelocityContext ctx = new VelocityContext(scenario.getContext().asMap());

    JSONObject result = step;
    result.keySet().forEach(key -> {
        if (result.get(key) instanceof String && result.getString(key).contains("$"))
        {
            try
            {
                String source = result.getString(key);
                source = source.replace("#", "#[[#]]#");

                StringWriter writer = new StringWriter();
                String id = step.has("id") ? step.get("id").toString() : step.get("eventId").toString();
                Velocity.evaluate(ctx, writer, id, source);

                String parsed = writer.toString();
                result.put(key, parsed);
            }
            catch (Exception e)
            {
                LOG.error(e.toString(), e);
            }
        }
    });
    return result;
}
 
Example #22
Source File: VelocityClassLoaderTest.java    From SimpleWeibo with Apache License 2.0 5 votes vote down vote up
/**
 * Make a different ClassLoader that loads the same URLs as this one, and use it to compile
 * an {@code @RetroWeibo} class. If Velocity loads its managers using the context class loader,
 * and that loader is still the original one that loaded this test, then it will find the
 * original copy of the Velocity classes rather than the one from the new loader, and fail.
 *
 * <p>This test assumes that the test class was loaded by a URLClassLoader and that that loader's
 * URLs also include the Velocity classes.
 */
public void testClassLoaderHack() throws Exception {
  URLClassLoader myLoader = (URLClassLoader) getClass().getClassLoader();
  URLClassLoader newLoader = new URLClassLoader(myLoader.getURLs(), myLoader.getParent());
  String velocityClassName = Velocity.class.getName();
  Class<?> myVelocity = myLoader.loadClass(velocityClassName);
  Class<?> newVelocity = newLoader.loadClass(velocityClassName);
  assertThat(myVelocity).isNotEqualTo(newVelocity);
  Runnable test = (Runnable) newLoader.loadClass(RunInClassLoader.class.getName()).newInstance();
  assertThat(test.getClass()).isNotEqualTo(RunInClassLoader.class);
  test.run();
}
 
Example #23
Source File: VelocityTemplate.java    From XBatis-Code-Generator with Apache License 2.0 5 votes vote down vote up
/**
 * 获取并解析模版
 * @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;
}
 
Example #24
Source File: MethodInvocationExceptionTestCase.java    From velocity-engine with Apache License 2.0 5 votes vote down vote up
/**
 * Runs the test :
 *
 *  uses the Velocity class to eval a string
 *  which accesses a method that throws an
 *  exception.
 *  @throws Exception
 */
public void testNormalMethodInvocationException ()
        throws Exception
{
    String template = "$woogie.doException() boing!";

    VelocityContext vc = new VelocityContext();

    vc.put("woogie", this );

    StringWriter w = new StringWriter();

    try
    {
        Velocity.evaluate( vc,  w, "test", template );
        fail("No exception thrown");
    }
    catch( MethodInvocationException mie )
    {
        log("Caught MIE (good!) :" );
        log("  reference = " + mie.getReferenceName() );
        log("  method    = " + mie.getMethodName() );

        Throwable t = mie.getCause();
        log("  throwable = " + t );

        if( t instanceof Exception)
        {
            log("  exception = " + t.getMessage() );
        }
    }
}
 
Example #25
Source File: WebServer.java    From tracing-framework with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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");
    }
}
 
Example #26
Source File: VelocityTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Test
public void testVelocity() {
    Velocity.init();
    final VelocityContext vContext = new VelocityContext();
    vContext.put("name", new String("Velocity"));

    final Template template = Velocity.getTemplate("target/test-classes/hello.vm");

    final StringWriter sw = new StringWriter();

    template.merge(vContext, sw);
}
 
Example #27
Source File: BaseEntityRenderer.java    From entando-core with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public String render(IApsEntity entity, String velocityTemplate, String langCode, boolean convertSpecialCharacters) {
	String renderedEntity = null;
	List<TextAttributeCharReplaceInfo> conversions = null;
	try {
		if (convertSpecialCharacters) {
			conversions = this.convertSpecialCharacters(entity, langCode);
		}
		Context velocityContext = new VelocityContext();
		EntityWrapper entityWrapper = this.getEntityWrapper(entity);
		entityWrapper.setRenderingLang(langCode);
		velocityContext.put(this.getEntityWrapperContextName(), entityWrapper);

		I18nManagerWrapper i18nWrapper = new I18nManagerWrapper(langCode, this.getI18nManager());
		velocityContext.put("i18n", i18nWrapper);
		StringWriter stringWriter = new StringWriter();
		boolean isEvaluated = Velocity.evaluate(velocityContext, stringWriter, "render", velocityTemplate);
		if (!isEvaluated) {
			throw new ApsSystemException("Rendering error");
		}
		stringWriter.flush();
		renderedEntity = stringWriter.toString();
	} catch (Throwable t) {
		_logger.error("Rendering error. entity {}", entity.getTypeCode(), t);
		//ApsSystemUtils.logThrowable(t, this, "render", "Rendering error");
		renderedEntity = "";
	} finally {
		if (convertSpecialCharacters && null != conversions) {
			this.replaceSpecialCharacters(conversions);
		}
	}
	return renderedEntity;
}
 
Example #28
Source File: ContextSafetyTestCase.java    From velocity-engine with Apache License 2.0 5 votes vote down vote up
public void setUp()
        throws Exception
{
    Velocity.reset();
    Velocity.setProperty(
            Velocity.FILE_RESOURCE_LOADER_PATH, FILE_RESOURCE_LOADER_PATH);

    Velocity.setProperty(
            Velocity.RUNTIME_LOG_INSTANCE, new TestLogger());

    Velocity.init();
}
 
Example #29
Source File: JpaMappingCodeGenerator.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Generate the JPA Mapping of one BusinessModel in one outputFile
 *
 * @param model      BusinessModel
 * @param outputFile File
 */
public void generateJpaMapping(BusinessModel model, boolean isUpdatableMapping) {

	logger.trace("IN");

	Velocity.setProperty("file.resource.loader.path", getTemplateDir().getAbsolutePath());
	Velocity.setProperty("runtime.log.logsystem.class", "org.apache.velocity.runtime.log.SimpleLog4JLogSystem");
	Velocity.setProperty("runtime.log.logsystem.log4j.category", "velocity");
	Velocity.setProperty("runtime.log.logsystem.log4j.logger", "velocity");

	JpaModel jpaModel = new JpaModel(model);
	generateBusinessTableMappings(jpaModel.getTables(), isUpdatableMapping);
	logger.info("Java files for tables of model [{}] succesfully created", model.getName());

	generateBusinessViewMappings(jpaModel.getViews(), isUpdatableMapping);
	logger.info("Java files for views of model [{}] succesfully created", model.getName());

	createLabelsFile(labelsTemplate, jpaModel);
	logger.info("Labels file for model [{}] succesfully created", model.getName());

	createPropertiesFile(propertiesTemplate, jpaModel);
	logger.info("Properties file for model [{}] succesfully created", model.getName());

	generatePersistenceUnitMapping(jpaModel);
	logger.info("Persistence unit for model [{}] succesfully created", model.getName());

	createCfieldsFile(cfieldsTemplate, jpaModel);
	logger.info("Calculated fields file for model [{}] succesfully created", model.getName());

	createRelationshipFile(relationshipsTemplate, jpaModel);
	logger.info("Relationships file for model [{}] succesfully created", model.getName());

	generateHierarchiesFile(hierarchiesTemplate, model);
	logger.info("Hierarchies file for model [{}] succesfully created", model.getName());

	logger.trace("OUT");
}
 
Example #30
Source File: BaseTestCase.java    From velocity-tools with Apache License 2.0 5 votes vote down vote up
protected void info(String msg)
{
    if (DEBUG)
    {
        if (engine == null)
        {
            Velocity.getLog().info(msg);
        }
        else
        {
            engine.getLog().info(msg);
        }
    }
}