Eclipse插件(RCP)整合Freemarker


FreeMarker

FreeMarker 是一款 模板引擎: 即一种基于模板和要改变的数据, 并用来生成输出文本(HTML网页,电子邮件,配置文件,源代码等)的通用工具。

一、引入依赖

eclipse 默认提供了 freemarker 依赖 org.eclipse.tools.templates.freemarker。打开 plugin.xml, 切换到 dependencies页面, 将其加入依赖。如下图:
在这里插入图片描述

二、初始画 Freemarker 配置

编码人员通常都有良好编码习惯,比如习惯性地把项目中的模板文件放在统一的文件夹中,如此会使得Freemarker 配置代码更加简单优雅。好习惯对代码质量起到了积极的作用。

2.1 自定义配置类

在一个app应用中一般需要一套配置就可以了,因此以单例模式设计并实现 freemarker 全局配置类。
FreemarkerConfig

package com.xzbd.rcp02.config;

import java.io.File;
import java.io.IOException;
import java.util.Objects;

import org.apache.commons.lang.StringUtils;
import org.eclipse.core.resources.IFile;

import com.xzbd.rcp02.exception.AppBaseException;
import com.xzbd.rcp02.util.WorkbenchUtil;
import freemarker.core.ParseException;
import freemarker.template.Configuration;
import freemarker.template.MalformedTemplateNameException;
import freemarker.template.Template;
import freemarker.template.TemplateExceptionHandler;
import freemarker.template.TemplateNotFoundException;

public class FreemarkerConfig {

	private static Configuration cfiguration;

	public static final String TMP_PATH = "/resources/templates";

	private FreemarkerConfig() {

	}
	
	/**
	 * <h1>获取模板</h1>
	 * @param filePath 模板相对路径,相对于{@code TMP_PATH},如a/b/c.ftl 实际路径为:${TMP_PATH}/a/b/c.ftl。即:/resources/templates/a/b/c.ftl
	 * @return
	 */
	public static Template getTemplate(String filePath) {
		Template tmp = null;
		if(StringUtils.isBlank(filePath)) {
			throw new AppBaseException("模板未找到,模板文件名为空");
		}
		if(Objects.isNull(cfiguration)) {
			throw new AppBaseException("模板引擎未初始化");
		}
		try {
			tmp =  cfiguration.getTemplate(filePath);
		} catch (Exception e) {
			throw new AppBaseException("获取模板失败,输入:" + filePath);
		}
		return tmp;
	}

	public static void init() {
		try {
			Configuration cfg = new Configuration(Configuration.VERSION_2_3_21);
			cfg.setDefaultEncoding("GBK");
			cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
			IFile tmpFile = WorkbenchUtil.getWorkSpaceFile(TMP_PATH);
			File tmpPath = WorkbenchUtil.getLocalSystemPath(tmpFile.getFullPath());
			if (!tmpPath.exists()) {
				throw new AppBaseException("配置文件不存在");
			}

			cfg.setDirectoryForTemplateLoading(tmpPath);
			cfg.setStrictSyntaxMode(true);
			cfiguration = cfg;
		} catch (Exception e) {
			throw new AppBaseException("freemarker配置 初始化失败" + (StringUtils.isBlank(e.getMessage())? "": "\r\n" + e.getMessage()));
		}
	}
}

2.2 初始化配置

根据设计,在应用启动成功后初始化配置,因此在类 ApplicationWorkbenchAdvisorpostStartup 方法中调用FreemarkerConfig.init 方法 。代码如下:

public class ApplicationWorkbenchAdvisor extends WorkbenchAdvisor {
	//省略  …… 
	
	@Override
	public void postStartup() {
		try {
			// 初始化模板引擎配置
			FreemarkerConfig.init();
		}catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	//省略  …… 
}

三、定义模板文件

根据配置类,freemarker 的模板文件放在 /resources/templates 文件夹下,其结构如下:
在这里插入图片描述
其中 test.ftl 文件内容如下:

<html>
<head>
  <title>Welcome!</title>
</head>
<body>
  <h1>Welcome ${user}!</h1>
  <p>Our latest product:
  <a href="${latestProduct.url}">${latestProduct.name}</a>!
</body>
</html>

注意: 如果打包后的app安装目录中没有 resource及其内部模板文件,请自行想办法将其复制到结果目录。这个很重要,也很容易忽略。如果程序报找不到模板文件,请在此处着手

四、使用 freemarker 生成代码

核心代码

		// 组织模板数据
		Map<String,Object> root = new HashMap();
		root.put("user", "Big Joe");
		Map latest = new HashMap();
		root.put("latestProduct", latest);
		latest.put("url", "products/greenmouse.html");
		latest.put("name", "green mouse");
		
		// 获取模板 ,freemarker 或找到 /resources/templates/test.ftl 模板文件
		Template template = FreemarkerConfig.getTemplate("test.ftl");
		// 定义输出流,
		Writer out = new OutputStreamWriter(new FileOutputStream("test.txt"), "utf-8");
		// 调用引擎生成文件
		template.process(functionLib, out);
		out.flush();
		if (out != null) {
		  out.close();
		}

生成结果

<html>
<head>
  <title>Welcome!</title>
</head>
<body>
  <h1>Welcome Big Joe!</h1>
  <p>Our latest product:
  <a href="products/greenmouse.html">green mouse</a>!
</body>
</html>

AppBaseException

package com.xzbd.rcp02.exception;

import org.apache.commons.lang.StringUtils;

public class AppBaseException extends RuntimeException {

    private static final String DEFAULT_MESSAGE = "系统异常";

    public AppBaseException() {
        super(DEFAULT_MESSAGE);
    }

    public AppBaseException(String message) {
        super(StringUtils.isNotBlank(message) ? message : DEFAULT_MESSAGE);
    }
}

WorkbenchUtil

package com.xzbd.rcp02.util;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

import org.apache.commons.lang.StringUtils;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IProjectDescription;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.IWorkspaceRunnable;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.OperationCanceledException;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.SubProgressMonitor;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.TreeSelection;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IPartService;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.internal.ErrorEditorPart;
import org.eclipse.ui.part.FileEditorInput;


public class WorkbenchUtil {

	public final static String GUID_REGEX_PATTERN = "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$";

	/**
	 * 获取工作空间
	 * 
	 * @return
	 */
	public static IWorkspace getWorkspace() {
		return ResourcesPlugin.getWorkspace();
	}

	/**
	 * 获取根工作空间
	 * 
	 * @return
	 */
	public static IWorkspaceRoot getWorkspaceRoot() {
		return getWorkspace().getRoot();
	}

	/**
	 * 获取工作空间中的文件
	 * 
	 * @param filePath
	 * @return
	 */
	public static IFile getWorkSpaceFile(String filePath) {
		return getWorkSpaceFile(new Path(filePath));
	}

	/**
	 * 获取工作空间中的文件
	 * 
	 * @param filePath 文件路径
	 * @return
	 */
	public static IFile getWorkSpaceFile(IPath filePath) {
		return getWorkspaceRoot().getFile(filePath);
	}

	
	/**
	 * 根据Eclipse虚拟路径获取系统资源路径
	 * 
	 * @param path Eclipse虚拟路径
	 * @return
	 */
	public static File getLocalSystemPath(IPath path) {
		// return getWorkspaceRoot().getLocation().append(path).toFile();
		return getLocalSystemPath(path.toString());
	}
	
	/**
	 * 根据Eclipse虚拟路径获取系统资源路径
	 * 
	 * @param path Eclipse虚拟路径 (相对路径)
	 * @return
	 */
	public static File getLocalSystemPath(String path) {
		// return getWorkspaceRoot().getLocation().append(path).toFile();
		return new File(getWorkspaceRoot().getLocation().toFile().getParentFile().toString() + "\\" + path);
	}
 

总结

以上就是 Eclipse插件中整合 FreeMarker 的所有内容,有不周之处,欢迎留言指正。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值