org.zodiac.template.freemarker.directive.AbstractDirective Maven / Gradle / Ivy
The newest version!
package org.zodiac.template.freemarker.directive;
import java.io.IOException;
import java.io.Writer;
import java.util.Map;
import org.zodiac.sdk.toolkit.util.lang.ArrayUtil;
import org.zodiac.sdk.toolkit.util.lang.StrUtil;
import freemarker.core.Environment;
import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapperBuilder;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateModel;
import freemarker.template.TemplateModelException;
public abstract class AbstractDirective implements TemplateDirectiveModel {
public static final String VARIABLE_NAME = "value";
public AbstractDirective() {
super();
}
public abstract String getName();
protected final TemplateModel wrapTemplateModel(Object value) throws TemplateModelException {
DefaultObjectWrapperBuilder builder = createBuilder();
return builder.build().wrap(value);
}
protected final void writeOut(Environment env, int content) throws IOException {
getWriter(env).write(content);
}
protected final void writeOut(Environment env, String content, int off, int len) throws IOException {
String _content = StrUtil.trimToNull(content);
if (null == _content) return;
getWriter(env).write(_content, off, len);
}
protected final void writeOut(Environment env, String content) throws IOException {
String _content = StrUtil.trimToNull(content);
if (null == _content) return;
getWriter(env).write(_content);
}
protected final void writeOut(Environment env, char[] content, int off, int len) throws IOException {
if (ArrayUtil.isEmptyArray(content)) return;
getWriter(env).write(content, off, len);
}
protected final void writeOut(Environment env, char[] content) throws IOException {
if (ArrayUtil.isEmptyArray(content)) return;
getWriter(env).write(content);
}
protected final DefaultObjectWrapperBuilder createBuilder() {
return new DefaultObjectWrapperBuilder(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
}
protected Writer getWriter(Environment env) {
return env.getOut();
}
@SuppressWarnings({ "rawtypes", "unchecked" })
protected final P parseParam(Environment env, Map params, String name, boolean required) throws TemplateModelException {
if (required) {
if (!params.containsKey(name)) {
throw new TemplateModelException(String.format("Param %s is required", name));
}
Object paramObj = params.get(name);
if (null == paramObj) {
throw new TemplateModelException(String.format("Param %s is required", name));
}
return (P)params.get(name);
} else {
return params.containsKey(name) ? (P)params.get(name) : null;
}
}
}