package util;
import java.io.File;
import java.io.StringReader;
import java.io.StringWriter;
import java.text.MessageFormat;
import java.util.Date;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.log4j.Logger;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateExceptionHandler;
/*************************************
* 类名称:字符串工具类
* 类功能:
*************************************/
public class StringUtil {
private static final Logger LOGGER = Logger.getLogger(StringUtil.class);
private static Pattern placeHolderPattern = Pattern.compile("\\$\\{(\\w+)\\}");
private static final Configuration FREEMARK_CONFIG = new Configuration(Configuration.VERSION_2_3_23);
static {
try {
FREEMARK_CONFIG.setDirectoryForTemplateLoading(new File("conf"));
FREEMARK_CONFIG.setDefaultEncoding("UTF-8");
FREEMARK_CONFIG.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
FREEMARK_CONFIG.setNumberFormat("#");
} catch (Exception e) {
LOGGER.error("初始化FREEMARKER配置出错", e);
}
}
/**
* 判断是否是空串
* @param str
* @return
*/
public static boolean isEmptyString(String str) {
return str == null || "".equals(str.trim());
}
/**
* 截取字符串
* @param str
* @param maxLen 最大长度
* @return
*/
public static String cutString(String str, int maxLen) {
if (str != null && str.length() > maxLen) {
return str.substring(0, maxLen);
}
return str;
}
/**
* 字符串匹配正则表达式
* @param target 目标字符串
* @param regExp 正则表达式
* @return 匹配上返回匹配的内容,否则返回null
*/
public static String macthPattern(String target, String regExp) {
Matcher matcher = Pattern.compile(regExp).matcher(target);
if (matcher.find()) {
return matcher.group();
}
return null;
}
/**
* 替换占位符
* @param source 源字符串
* @param params 参数
* @return
*/
public static String replacePlaceholder(String source, Map<String, Object> params) {
String result = source;
Matcher matcher = placeHolderPattern.matcher(source);
while (matcher.find()) {
String hodlerName = matcher.group(1);
if (params.containsKey(hodlerName)) {
Object value = params.get(hodlerName);
result = result.replace(matcher.group(), value == null ? "" : value.toString());
}
}
return result;
}
/**
* 替换占位符补充方法(这里只做简单的引入,灵活应用可以再)
* @return
*/
public static String replacePlaceholder2(){
String result ="";
String stringFormat = "lexical error at position %s, encountered %s, expected %s ";
String resultFormat = String.format(stringFormat, 123, 100, 456);
String messageFormat ="lexical error at position {0}, encountered {1}, expected {2}";
String resultMessage = MessageFormat.format(messageFormat, new Date(), 100, 456);
LOGGER.info("\nstringFormat:"+stringFormat+"\n"+"messageFormat:"+messageFormat+"\n");
return result = "\n"+ resultFormat + ",\n" +resultMessage;
}
/**
* 根据模板生成文本
* @param template 模板
* @param data 数据
* @return
*/
public static String generateText(File templateFile, Map<String, Object> data) {
try {
Configuration conf = new Configuration(Configuration.VERSION_2_3_23);
String dir = templateFile.getAbsolutePath();
conf.setDirectoryForTemplateLoading(new File(dir.substring(0,dir.lastIndexOf("\\")+1)));
Template temp = conf.getTemplate(dir.substring(dir.lastIndexOf("\\"),dir.length()));
//template参数需要将模板文件读取进来转化为字符串传入,这边还要创建一个输入流比较麻烦就不用这种方法了。
//Template temp = new Template(null, template,cof);
StringWriter out = new StringWriter();
temp.process(data, out);
out.close();
return out.toString();
} catch (Throwable t) {
LOGGER.error("根据模板生成文本出错" + ", data=" + data, t);
return "失败";
}
}
}
String工具测试类
package utilTest;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import org.apache.log4j.Logger;
import org.junit.Test;
import util.StringUtil;
public class StringUtilTest {
private static final Logger LOGGER = Logger.getLogger(StringUtilTest.class);
@Test
public void testIsEmpty() {
String str = "";
LOGGER.info(StringUtil.isEmptyString(str));
}
@Test
public void testCutString(){
String str = "student";
LOGGER.info(StringUtil.cutString(str, str.length()-2));
}
@Test
public void testMachePattern(){
String regExp = "Ipran_(.*)_txt";
String target = "Ipran_20180101_txt";
String target1 = "Ipran_20180101_cvs";
LOGGER.info(StringUtil.macthPattern(target, regExp));//输出为Ipran_20180101_txt
LOGGER.info(StringUtil.macthPattern(target1, regExp));//输出为空
}
@Test
public void testReplacePlaceholder(){
String source = "我是${name},我来自${place},今年${age}岁";
Map<String, Object> params = new HashMap<String,Object>();
params.put("name", "张三");
params.put("place", "福建");
params.put("age", "28");
LOGGER.info(StringUtil.replacePlaceholder(source, params));
}
@Test
public void testReplacePlaceholder2(){
LOGGER.info(StringUtil.replacePlaceholder2());
}
@Test
public void testGenerateText(){
File templateFile = new File("conf/enop.ftl");//用于生成指定格式的模板(例如接口的请求报文)
Map<String, Object> datas = new HashMap<String,Object>();
datas.put("ONUIP", "172.0.0.1");
LOGGER.info(StringUtil.generateText(templateFile, datas));
}
}
(3、epon.ftl格式文件)
<#if ONUIP??&&ONUIP?length gt 0>LST-DEVINFO::ONUIP=${ONUIP}:CTAG::;
<#else>LST-DEVINFO::OLTID=${OLTID}
<#if PONID??&&PONID? length gt 0>,PONID=${PONID},ONUIDTYPE=${ONUIDTYPE},ONUID=${ONUID}
</#if>:CTAG::;
</#if>
(4、项目结构)