Skip to content
This repository was archived by the owner on Nov 27, 2023. It is now read-only.

Commit 004fe6b

Browse files
committed
增加Freemarker类型的动态数据
1 parent a1c87af commit 004fe6b

File tree

1 file changed

+90
-0
lines changed

1 file changed

+90
-0
lines changed
Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
/*
2+
* Copyright 2002-2007 the original author or authors.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package org.suren.autotest.web.framework.data;
18+
19+
import java.io.BufferedWriter;
20+
import java.io.ByteArrayOutputStream;
21+
import java.io.IOException;
22+
import java.io.OutputStreamWriter;
23+
import java.io.Writer;
24+
import java.util.Map;
25+
26+
import org.springframework.stereotype.Component;
27+
28+
import freemarker.cache.StringTemplateLoader;
29+
import freemarker.template.Configuration;
30+
import freemarker.template.DefaultObjectWrapper;
31+
import freemarker.template.Template;
32+
import freemarker.template.TemplateException;
33+
34+
/**
35+
* @author suren
36+
* @date 2017年3月25日 上午9:28:47
37+
*/
38+
@Component
39+
public class FreemarkerDynamicData implements DynamicData
40+
{
41+
private Map<String, Object> globalData;
42+
43+
private static final String TMP_NAME = "freemarker";
44+
45+
@Override
46+
public String getValue(String orginData)
47+
{
48+
StringTemplateLoader templateLoader = new StringTemplateLoader();
49+
templateLoader.putTemplate(TMP_NAME, orginData);
50+
51+
Configuration configuration = new Configuration();
52+
configuration.setTemplateLoader(templateLoader);
53+
configuration.setObjectWrapper(new DefaultObjectWrapper());
54+
configuration.setDefaultEncoding("UTF-8");
55+
56+
try
57+
{
58+
Template template = configuration.getTemplate(TMP_NAME);
59+
60+
ByteArrayOutputStream out = new ByteArrayOutputStream();
61+
Writer writer = new BufferedWriter(new OutputStreamWriter(out)) ;
62+
template.process(globalData, writer);
63+
64+
return out.toString("utf-8");
65+
}
66+
catch (IOException e)
67+
{
68+
e.printStackTrace();
69+
}
70+
catch (TemplateException e)
71+
{
72+
e.printStackTrace();
73+
}
74+
75+
return null;
76+
}
77+
78+
@Override
79+
public String getType()
80+
{
81+
return TMP_NAME;
82+
}
83+
84+
@Override
85+
public void setData(Map<String, Object> data)
86+
{
87+
this.globalData = data;
88+
}
89+
90+
}

0 commit comments

Comments
 (0)