Adding FreemarkerConfigurationLoader to allow freemarker to be used in other parts of the system.

This commit is contained in:
bdc34 2010-11-08 21:49:07 +00:00
parent 7f62ea5087
commit d1c053ff97
8 changed files with 299 additions and 134 deletions

View file

@ -0,0 +1,161 @@
/* $This file is distributed under the terms of the license in /doc/license.txt$ */
package edu.cornell.mannlib.vitro.webapp.controller.freemarker;
import java.io.File;
import java.io.IOException;
import java.util.Map;
import javax.servlet.ServletContext;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import edu.cornell.mannlib.vitro.webapp.ConfigurationProperties;
import edu.cornell.mannlib.vitro.webapp.beans.Portal;
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
import freemarker.cache.ClassTemplateLoader;
import freemarker.cache.FileTemplateLoader;
import freemarker.cache.MultiTemplateLoader;
import freemarker.cache.TemplateLoader;
import freemarker.ext.beans.BeansWrapper;
import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.TemplateException;
public class FreemarkerConfigurationLoader {
private static final Log log = LogFactory.getLog(FreemarkerConfigurationLoader.class);
private ServletContext context;
public FreemarkerConfigurationLoader( ServletContext context){
this.context = context;
context.setAttribute("FreemarkerConfigurationLoader", this);
}
/**
* @return Under serious error conditions this will return null.
*/
public static FreemarkerConfigurationLoader getFreemarkerConfigurationLoader(ServletContext context){
if( context!=null){
FreemarkerConfigurationLoader fcl = (FreemarkerConfigurationLoader)
context.getAttribute("FreemarkerConfigurationLoader");
if( fcl == null ){
log.error("Must be constructed before calling " +
"getFreemarkerConfigurationLoader(), usually this is done by FreemarkerSetup");
return null;
}
return fcl;
}else{
log.error("getFreemarkerConfigurationLoader() must not be called with a null context");
return null;
}
}
public Configuration getConfig(VitroRequest vreq) {
String themeDir = getThemeDir(vreq.getPortal());
return getConfigForTheme(themeDir);
}
protected String getThemeDir(Portal portal) {
return portal.getThemeDir().replaceAll("/$", "");
}
protected Configuration getConfigForTheme(String themeDir) {
// The template loader is theme-specific because it specifies the theme template directory as a location to
// load templates from. Thus configurations are associated with themes rather than portals.
@SuppressWarnings("unchecked")
Map<String, Configuration> themeToConfigMap = (Map<String, Configuration>) context.getAttribute("themeToConfigMap");
if( themeToConfigMap == null ) {
log.error("The templating system is not configured correctly. Make sure that you have the FreemarkerSetup context listener in your web.xml.");
// We'll end up with a blank page as well as errors in the log, which is probably fine.
// Doesn't seem like we should throw a checked exception in this case.
return null;
} else if (themeToConfigMap.containsKey(themeDir)) {
return themeToConfigMap.get(themeDir);
} else {
Configuration config = getNewConfig(themeDir);
themeToConfigMap.put(themeDir, config);
return config;
}
}
private Configuration getNewConfig(String themeDir) {
Configuration config = new Configuration();
String buildEnv = ConfigurationProperties.getProperty("Environment.build");
log.debug("Current build environment: " + buildEnv);
if ("development".equals(buildEnv)) { // Set Environment.build = development in deploy.properties
log.debug("Disabling Freemarker template caching in development build.");
config.setTemplateUpdateDelay(0); // no template caching in development
} else {
int delay = 60;
log.debug("Setting Freemarker template cache update delay to " + delay + ".");
config.setTemplateUpdateDelay(delay); // in seconds; Freemarker default is 5
}
// Specify how templates will see the data model.
// The default wrapper exposes set methods unless exposure level is set.
// By default we want to block exposure of set methods.
BeansWrapper wrapper = new DefaultObjectWrapper();
wrapper.setExposureLevel(BeansWrapper.EXPOSE_PROPERTIES_ONLY);
config.setObjectWrapper(wrapper);
// Set some formatting defaults. These can be overridden at the template
// or environment (template-processing) level, or for an individual
// token by using built-ins.
config.setLocale(java.util.Locale.US);
String dateFormat = "M/d/yyyy";
config.setDateFormat(dateFormat);
String timeFormat = "hh:mm a";
config.setTimeFormat(timeFormat);
config.setDateTimeFormat(dateFormat + " " + timeFormat);
//config.setNumberFormat("#,##0.##");
try {
config.setSetting("url_escaping_charset", "ISO-8859-1");
} catch (TemplateException e) {
log.error("Error setting value for url_escaping_charset.");
}
config.setTemplateLoader(getTemplateLoader(config, themeDir));
return config;
}
// Define template locations. Template loader will look first in the theme-specific
// location, then in the vitro location.
protected final TemplateLoader getTemplateLoader(Configuration config, String themeDir) {
String themeTemplatePath = context.getRealPath(themeDir) + "/templates";
String vitroTemplatePath = context.getRealPath("/templates/freemarker");
try {
TemplateLoader[] loaders;
FlatteningTemplateLoader vitroFtl = new FlatteningTemplateLoader(new File(vitroTemplatePath));
ClassTemplateLoader ctl = new ClassTemplateLoader(getClass(), "");
File themeTemplateDir = new File(themeTemplatePath);
// Handle the case where there's no theme template directory gracefully
if (themeTemplateDir.exists()) {
FileTemplateLoader themeFtl = new FileTemplateLoader(themeTemplateDir);
loaders = new TemplateLoader[] { themeFtl, vitroFtl, ctl };
} else {
loaders = new TemplateLoader[] { vitroFtl, ctl };
}
MultiTemplateLoader mtl = new MultiTemplateLoader(loaders);
return mtl;
} catch (IOException e) {
log.error("Error creating template loaders");
return null;
}
}
}

View file

@ -2,7 +2,6 @@
package edu.cornell.mannlib.vitro.webapp.controller.freemarker;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
@ -11,7 +10,6 @@ import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@ -22,7 +20,6 @@ import org.apache.commons.logging.LogFactory;
import com.hp.hpl.jena.rdf.model.Model;
import edu.cornell.mannlib.vedit.beans.LoginStatusBean;
import edu.cornell.mannlib.vitro.webapp.ConfigurationProperties;
import edu.cornell.mannlib.vitro.webapp.beans.ApplicationBean;
import edu.cornell.mannlib.vitro.webapp.beans.Portal;
import edu.cornell.mannlib.vitro.webapp.config.RevisionInfoBean;
@ -37,15 +34,10 @@ import edu.cornell.mannlib.vitro.webapp.web.PortalWebUtil;
import edu.cornell.mannlib.vitro.webapp.web.templatemodels.files.Scripts;
import edu.cornell.mannlib.vitro.webapp.web.templatemodels.files.Stylesheets;
import edu.cornell.mannlib.vitro.webapp.web.templatemodels.menu.TabMenu;
import freemarker.cache.ClassTemplateLoader;
import freemarker.cache.FileTemplateLoader;
import freemarker.cache.MultiTemplateLoader;
import freemarker.cache.TemplateLoader;
import freemarker.ext.beans.BeansWrapper;
import freemarker.ext.servlet.AllHttpScopesHashModel;
import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;
import freemarker.template.TemplateModelException;
@ -75,7 +67,7 @@ public class FreemarkerHttpServlet extends VitroHttpServlet {
}
public void doGet( HttpServletRequest request, HttpServletResponse response )
throws IOException, ServletException {
throws IOException, ServletException {
super.doGet(request,response);
@ -95,10 +87,10 @@ public class FreemarkerHttpServlet extends VitroHttpServlet {
doResponse(vreq, response, responseValues);
} catch (Throwable e) {
log.error("FreeMarkerHttpServlet could not forward to view.", e);
}
}
} catch (Throwable e) {
log.error("FreeMarkerHttpServlet could not forward to view.", e);
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
@ -106,105 +98,9 @@ public class FreemarkerHttpServlet extends VitroHttpServlet {
}
protected Configuration getConfig(VitroRequest vreq) {
String themeDir = getThemeDir(vreq.getPortal());
return getConfigForTheme(themeDir);
}
protected Configuration getConfigForTheme(String themeDir) {
// The template loader is theme-specific because it specifies the theme template directory as a location to
// load templates from. Thus configurations are associated with themes rather than portals.
@SuppressWarnings("unchecked")
Map<String, Configuration> themeToConfigMap = (Map<String, Configuration>) (getServletContext().getAttribute("themeToConfigMap"));
if( themeToConfigMap == null ) {
log.error("The templating system is not configured correctly. Make sure that you have the FreemarkerSetup context listener in your web.xml.");
// We'll end up with a blank page as well as errors in the log, which is probably fine.
// Doesn't seem like we should throw a checked exception in this case.
return null;
} else if (themeToConfigMap.containsKey(themeDir)) {
return themeToConfigMap.get(themeDir);
} else {
Configuration config = getNewConfig(themeDir);
themeToConfigMap.put(themeDir, config);
return config;
}
}
private Configuration getNewConfig(String themeDir) {
Configuration config = new Configuration();
String buildEnv = ConfigurationProperties.getProperty("Environment.build");
log.debug("Current build environment: " + buildEnv);
if ("development".equals(buildEnv)) { // Set Environment.build = development in deploy.properties
log.debug("Disabling Freemarker template caching in development build.");
config.setTemplateUpdateDelay(0); // no template caching in development
} else {
int delay = 60;
log.debug("Setting Freemarker template cache update delay to " + delay + ".");
config.setTemplateUpdateDelay(delay); // in seconds; Freemarker default is 5
}
// Specify how templates will see the data model.
// The default wrapper exposes set methods unless exposure level is set.
// By default we want to block exposure of set methods.
BeansWrapper wrapper = new DefaultObjectWrapper();
wrapper.setExposureLevel(BeansWrapper.EXPOSE_PROPERTIES_ONLY);
config.setObjectWrapper(wrapper);
// Set some formatting defaults. These can be overridden at the template
// or environment (template-processing) level, or for an individual
// token by using built-ins.
config.setLocale(java.util.Locale.US);
String dateFormat = "M/d/yyyy";
config.setDateFormat(dateFormat);
String timeFormat = "hh:mm a";
config.setTimeFormat(timeFormat);
config.setDateTimeFormat(dateFormat + " " + timeFormat);
//config.setNumberFormat("#,##0.##");
try {
config.setSetting("url_escaping_charset", "ISO-8859-1");
} catch (TemplateException e) {
log.error("Error setting value for url_escaping_charset.");
}
config.setTemplateLoader(getTemplateLoader(config, themeDir));
return config;
}
// Define template locations. Template loader will look first in the theme-specific
// location, then in the vitro location.
protected final TemplateLoader getTemplateLoader(Configuration config, String themeDir) {
ServletContext context = getServletContext();
String themeTemplatePath = context.getRealPath(themeDir) + "/templates";
String vitroTemplatePath = context.getRealPath("/templates/freemarker");
try {
TemplateLoader[] loaders;
FlatteningTemplateLoader vitroFtl = new FlatteningTemplateLoader(new File(vitroTemplatePath));
ClassTemplateLoader ctl = new ClassTemplateLoader(getClass(), "");
File themeTemplateDir = new File(themeTemplatePath);
// Handle the case where there's no theme template directory gracefully
if (themeTemplateDir.exists()) {
FileTemplateLoader themeFtl = new FileTemplateLoader(themeTemplateDir);
loaders = new TemplateLoader[] { themeFtl, vitroFtl, ctl };
} else {
loaders = new TemplateLoader[] { vitroFtl, ctl };
}
MultiTemplateLoader mtl = new MultiTemplateLoader(loaders);
return mtl;
} catch (IOException e) {
log.error("Error creating template loaders");
return null;
}
FreemarkerConfigurationLoader loader =
FreemarkerConfigurationLoader.getFreemarkerConfigurationLoader(getServletContext());
return loader.getConfig(vreq);
}
protected boolean requiresLogin() {
@ -357,7 +253,7 @@ public class FreemarkerHttpServlet extends VitroHttpServlet {
// We can't use shared variables in the Freemarker configuration to store anything
// except theme-specific data, because multiple portals or apps might share the same theme. So instead
// we'll get all the shared variables here, and put them in both root and body maps.
protected Map<String, Object> getSharedVariables(VitroRequest vreq, Map<String, Object> bodyMap) {
public Map<String, Object> getSharedVariables(VitroRequest vreq, Map<String, Object> bodyMap) {
Map<String, Object> map = new HashMap<String, Object>();
@ -544,13 +440,13 @@ public class FreemarkerHttpServlet extends VitroHttpServlet {
return copyright;
}
private final Map<String, Object> getRevisionInfo(UrlBuilder urlBuilder) {
Map<String, Object> map = new HashMap<String, Object>();
map.put("label", RevisionInfoBean.getBean(getServletContext())
.getReleaseLabel());
map.put("moreInfoUrl", urlBuilder.getPortalUrl("/revisionInfo"));
return map;
}
private final Map<String, Object> getRevisionInfo(UrlBuilder urlBuilder) {
Map<String, Object> map = new HashMap<String, Object>();
map.put("label", RevisionInfoBean.getBean(getServletContext())
.getReleaseLabel());
map.put("moreInfoUrl", urlBuilder.getPortalUrl("/revisionInfo"));
return map;
}
// Subclasses may override. This serves as a default.
protected String getTitle(String siteName) {
@ -567,7 +463,7 @@ public class FreemarkerHttpServlet extends VitroHttpServlet {
}
protected String mergeMapToTemplate(String templateName, Map<String, Object> map, Configuration config) {
return mergeToTemplate(templateName, map, config).toString();
return mergeToTemplate(templateName, map, config).toString();
}
protected String mergeResponseValuesToTemplate(ResponseValues values, Configuration config) {

View file

@ -26,6 +26,8 @@ public class FreemarkerSetup implements ServletContextListener {
FreemarkerComponentGenerator.setServletContext(sc);
UrlBuilder.contextPath = sc.getContextPath();
FreemarkerConfigurationLoader loader = new FreemarkerConfigurationLoader(sc);
log.info("Freemarker templating system initialized.");
}

View file

@ -0,0 +1,26 @@
package edu.cornell.mannlib.vitro.webapp.edit.elements;
import java.util.Map;
import com.hp.hpl.jena.rdf.model.Literal;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.EditConfiguration;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.EditSubmission;
import freemarker.template.Configuration;
/**
* All classes that implement this interface must have a public empty constructor that
* will be called with using reflection.
*/
public interface EditElement {
/**
* This is a method to get a map of variable name to Literal value from the submitted form.
*/
public Map<String,Literal>
getLiterals(String fieldName, EditConfiguration editConfig, Map<String,String[]> queryParameters );
/**
* This is a method to generate the HTML output for a form element. It should use a freemarker template
* to produce the output.
*/
public String draw(String fieldName, EditConfiguration editConfig, EditSubmission editSub, Configuration fmConfig);
}

View file

@ -8,7 +8,6 @@ import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Calendar;
import javax.servlet.http.HttpSession;
@ -28,6 +27,7 @@ import com.hp.hpl.jena.rdf.model.ResourceFactory;
import com.hp.hpl.jena.vocabulary.XSD;
import edu.cornell.mannlib.vitro.webapp.edit.EditLiteral;
import edu.cornell.mannlib.vitro.webapp.edit.elements.EditElement;
public class EditSubmission {
private String editKey;
@ -108,7 +108,9 @@ public class EditSubmission {
} else {
log.debug("time fields for parameter " + var + " were not on form" );
}
} else {
} else if( field.getEditElement() != null ){
literalsFromForm.putAll( getLiteralForField(var,editConfig,queryParameters));
}else{
String[] valuesArray = queryParameters.get(var);
List<String> valueList = (valuesArray != null) ? Arrays.asList(valuesArray) : null;
if( valueList != null && valueList.size() > 0 ) {
@ -154,6 +156,21 @@ public class EditSubmission {
}
/**
* Get the literals for the field using the field's special editElement.
* @param var
* @param editConfig
* @param queryParameters
* @return
*/
private Map<? extends String, ? extends Literal> getLiteralForField(
String var, EditConfiguration editConfig,
Map<String, String[]> queryParameters) {
Field field = editConfig.getField(var);
EditElement ee = field.getEditElement();
return ee.getLiterals(var, editConfig, queryParameters);
}
public EditSubmission(Map<String, String[]> queryParameters, EditConfiguration editConfig,
Map<String, List<FileItem>> fileItems) {
this(queryParameters,editConfig);

View file

@ -2,6 +2,8 @@
package edu.cornell.mannlib.vitro.webapp.edit.n3editing;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
@ -14,6 +16,8 @@ import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import edu.cornell.mannlib.vitro.webapp.edit.elements.EditElement;
public class Field {
public enum OptionsType {
@ -51,6 +55,11 @@ public class Field {
*/
private OptionsType optionsType;
/**
* Special class to use for option type
*/
private Class customOptionType;
/**
* Used for building Options when OptionsType is INDIVIDUALS_VIA_OBJECT_PROPERTY
*/
@ -106,6 +115,11 @@ public class Field {
private Map<String, String> queryForExisting;
/**
* Property for special edit element.
*/
private EditElement editElement=null;;
/* *********************** Constructors ************************** */
public Field(String config, String varName) {
@ -229,7 +243,32 @@ public class Field {
setOptionsType(Field.OptionsType.DATE);
} else if ("TIME".equalsIgnoreCase(s)) {
setOptionsType(Field.OptionsType.TIME);
} else if ("UNDEFINED".equalsIgnoreCase(s) || s == null || s.isEmpty()){
setOptionsType(Field.OptionsType.UNDEFINED);
} else {
setSpecalOptionType(s);
}
}
private void setSpecalOptionType(String s) {
try {
Class clz = Class.forName(s);
Object obj = clz.newInstance();
editElement = (EditElement)obj;
} catch (ClassNotFoundException e) {
log.error("Java Class " + s + " not found for field " + name);
setOptionsType(Field.OptionsType.UNDEFINED);
} catch (SecurityException e) {
log.error("Problem with Java Class " + s + " for field " + name, e);
setOptionsType(Field.OptionsType.UNDEFINED);
} catch (IllegalArgumentException e) {
log.error("Problem with Java Class " + s + " for field " + name, e);
setOptionsType(Field.OptionsType.UNDEFINED);
} catch (InstantiationException e) {
log.error("Problem with Java Class " + s + " for field " + name, e);
setOptionsType(Field.OptionsType.UNDEFINED);
} catch (IllegalAccessException e) {
log.error("Problem with Java Class " + s + " for field " + name, e);
setOptionsType(Field.OptionsType.UNDEFINED);
}
}
@ -322,5 +361,8 @@ public class Field {
return copy;
}
public EditElement getEditElement(){
return editElement;
}
}

View file

@ -210,4 +210,7 @@ public class NamespaceMapperJena extends StatementListener implements
return namespaceToPrefixMap.get(namespace);
}
public String toString(){
return namespaceToPrefixMap.toString();
}
}

View file

@ -39,6 +39,7 @@ import edu.cornell.mannlib.vitro.webapp.beans.ObjectProperty;
import edu.cornell.mannlib.vitro.webapp.beans.VClass;
import edu.cornell.mannlib.vitro.webapp.controller.Controllers;
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
import edu.cornell.mannlib.vitro.webapp.controller.freemarker.FreemarkerConfigurationLoader;
import edu.cornell.mannlib.vitro.webapp.dao.WebappDaoFactory;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.EditConfiguration;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.EditSubmission;
@ -47,6 +48,7 @@ import edu.cornell.mannlib.vitro.webapp.edit.n3editing.SelectListGenerator;
import edu.cornell.mannlib.vitro.webapp.search.beans.ProhibitedFromSearch;
import edu.cornell.mannlib.vitro.webapp.utils.StringUtils;
import edu.cornell.mannlib.vitro.webapp.web.DisplayVocabulary;
import freemarker.template.Configuration;
/**
* This tag will build an option list for individuals of a VClass.
@ -391,21 +393,25 @@ public class InputElementFormattingTag extends TagSupport {
log.error("Error in doStartTag: input element id is blank or not specified.");
}
HttpSession session = pageContext.getSession();
EditConfiguration editConfig = EditConfiguration.getConfigFromSession(session,(HttpServletRequest) pageContext.getRequest());
EditSubmission editSub = EditSubmission.getEditSubmissionFromSession(session,editConfig);
VitroRequest vreq = new VitroRequest((HttpServletRequest)pageContext.getRequest());
WebappDaoFactory wdf;
if (editConfig != null) {
wdf = editConfig.getWdfSelectorForOptons().getWdf(
(HttpServletRequest)pageContext.getRequest(),
pageContext.getServletContext());
} else {
VitroRequest vreq = new VitroRequest((HttpServletRequest)pageContext.getRequest());
wdf = vreq.getWebappDaoFactory();
}
//get freemarker Configuration
FreemarkerConfigurationLoader fConfigLoader
= FreemarkerConfigurationLoader.getFreemarkerConfigurationLoader(pageContext.getServletContext());
Configuration fmConfig = fConfigLoader.getConfig(vreq);
/* populate the pieces */
String classStr = doClass();
String disabledStr = doDisabled();
@ -423,8 +429,16 @@ public class InputElementFormattingTag extends TagSupport {
if (definitionTags) { out.println("</dt>"); }
}
// bdc34 2010-11-08 field may be null
Field field = editConfig == null ? null : editConfig.getField(getId());
/* bdc34 2010-11-08 : this is odd, I'm having problems with the submit on this next line because
* it is not a field in the editConfig. This wasn't happening before. */
// if( field == null ){
// log.error("could not get field for id " + getId());
// return SKIP_BODY;
// }
// set ProhibitedFromSearch object so picklist doesn't show
// individuals from classes that should be hidden from list views
@ -438,14 +452,14 @@ public class InputElementFormattingTag extends TagSupport {
editConfig.setProhibitedFromSearch(pfs);
}
if( getType().equalsIgnoreCase("date") ||
if( field != null && field.getEditElement() != null ){
out.print( field.getEditElement().draw(getId(), editConfig, editSub, fmConfig));
}else if( getType().equalsIgnoreCase("date") ||
(field != null && field.getRangeDatatypeUri() != null && field.getRangeDatatypeUri().equals(XSD.date.getURI())) ){
//if its a dataprop that should be a string override type and use date picker
if (definitionTags) { out.print("<dg>"); }
out.print( generateHtmlForDate(getId(),editConfig,editSub) );
if (definitionTags) { out.print("</dg>"); }
} else if ( getType().equalsIgnoreCase("time") ||
(field != null && field.getRangeDatatypeUri() != null && field.getRangeDatatypeUri().equals(XSD.time.getURI())) ) {
if (definitionTags) { out.print("<dd>"); }
@ -623,6 +637,10 @@ public class InputElementFormattingTag extends TagSupport {
return SKIP_BODY;
}
private Map<String, String> getTypesForCreateNew(
EditConfiguration editConfig, WebappDaoFactory wdf) {
ObjectProperty op =