use of freemarker.ext.servlet.ServletContextHashModel in project spring-framework by spring-projects.
the class FreeMarkerView method initServletContext.
/**
* Invoked on startup. Looks for a single FreeMarkerConfig bean to
* find the relevant Configuration for this factory.
* <p>Checks that the template for the default Locale can be found:
* FreeMarker will check non-Locale-specific templates if a
* locale-specific one is not found.
* @see freemarker.cache.TemplateCache#getTemplate
*/
@Override
protected void initServletContext(ServletContext servletContext) throws BeansException {
if (getConfiguration() != null) {
this.taglibFactory = new TaglibFactory(servletContext);
} else {
FreeMarkerConfig config = autodetectConfiguration();
setConfiguration(config.getConfiguration());
this.taglibFactory = config.getTaglibFactory();
}
GenericServlet servlet = new GenericServletAdapter();
try {
servlet.init(new DelegatingServletConfig());
} catch (ServletException ex) {
throw new BeanInitializationException("Initialization of GenericServlet adapter failed", ex);
}
this.servletContextHashModel = new ServletContextHashModel(servlet, getObjectWrapper());
}
use of freemarker.ext.servlet.ServletContextHashModel in project entando-core by entando.
the class AbstractTestExecutorService method createModel.
protected TemplateModel createModel(ObjectWrapper wrapper) throws Throwable {
HttpServletRequest request = super.getRequestContext().getRequest();
HttpServletResponse response = super.getRequestContext().getResponse();
ServletContext servletContext = request.getSession().getServletContext();
// super.createModel(wrapper, servletContext, request, response);
AllHttpScopesHashModel hashModel = new AllHttpScopesHashModel(wrapper, servletContext, request);
ControllerServlet servlet = new ControllerServlet();
MockServletConfig config = new MockServletConfig(servletContext);
servlet.init(config);
ServletContextHashModel newServletContextModel = new ServletContextHashModel(servlet, wrapper);
ServletContextHashModel servletContextModel = new ServletContextHashModel(servlet, wrapper);
servletContext.setAttribute(ATTR_APPLICATION_MODEL, servletContextModel);
TaglibFactory taglibs = new TaglibFactory(servletContext);
servletContext.setAttribute(ATTR_JSP_TAGLIBS_MODEL, taglibs);
hashModel.putUnlistedModel(FreemarkerServlet.KEY_APPLICATION, newServletContextModel);
hashModel.putUnlistedModel(FreemarkerServlet.KEY_APPLICATION_PRIVATE, newServletContextModel);
hashModel.putUnlistedModel(FreemarkerServlet.KEY_JSP_TAGLIBS, taglibs);
HttpRequestHashModel requestModel = new HttpRequestHashModel(request, response, wrapper);
request.setAttribute(ATTR_REQUEST_MODEL, requestModel);
hashModel.putUnlistedModel(FreemarkerServlet.KEY_REQUEST_PRIVATE, requestModel);
return hashModel;
}
use of freemarker.ext.servlet.ServletContextHashModel in project nutzboot by nutzam.
the class FreemarkerView method jspTaglibs.
protected void jspTaglibs(ServletContext servletContext, HttpServletRequest request, HttpServletResponse response, Map<String, Object> model, ObjectWrapper wrapper) {
synchronized (servletContext) {
ServletContextHashModel servletContextModel = (ServletContextHashModel) servletContext.getAttribute(ATTR_APPLICATION_MODEL);
if (Lang.isEmpty(servletContextModel)) {
GenericServlet servlet = JspSupportServlet.jspSupportServlet;
if (!Lang.isEmpty(servlet)) {
servletContextModel = new ServletContextHashModel(servlet, wrapper);
servletContext.setAttribute(ATTR_APPLICATION_MODEL, servletContextModel);
TaglibFactory taglibs = new TaglibFactory(servletContext);
servletContext.setAttribute(ATTR_JSP_TAGLIBS_MODEL, taglibs);
}
}
model.put(KEY_APPLICATION, servletContextModel);
TemplateModel tempModel = (TemplateModel) servletContext.getAttribute(ATTR_JSP_TAGLIBS_MODEL);
model.put(KEY_JSP_TAGLIBS, tempModel);
}
HttpSession session = request.getSession(false);
if (!Lang.isEmpty(session)) {
model.put(KEY_SESSION_MODEL, new HttpSessionHashModel(session, wrapper));
}
HttpRequestHashModel requestModel = (HttpRequestHashModel) request.getAttribute(ATTR_REQUEST_MODEL);
if (Lang.isEmpty(requestModel) || !Lang.equals(requestModel.getRequest(), request)) {
requestModel = new HttpRequestHashModel(request, response, wrapper);
request.setAttribute(ATTR_REQUEST_MODEL, requestModel);
}
model.put(KEY_REQUEST_MODEL, requestModel);
HttpRequestParametersHashModel reqParametersModel = (HttpRequestParametersHashModel) request.getAttribute(ATTR_REQUEST_PARAMETERS_MODEL);
if (Lang.isEmpty(reqParametersModel) || !Lang.equals(requestModel.getRequest(), request)) {
reqParametersModel = new HttpRequestParametersHashModel(request);
request.setAttribute(ATTR_REQUEST_PARAMETERS_MODEL, reqParametersModel);
}
model.put(KEY_REQUEST_PARAMETER_MODEL, reqParametersModel);
Throwable exception = (Throwable) request.getAttribute("javax.servlet.error.exception");
if (Lang.isEmpty(exception)) {
exception = (Throwable) request.getAttribute("javax.servlet.error.JspException");
}
if (!Lang.isEmpty(exception)) {
model.put(KEY_EXCEPTION, exception);
}
}
use of freemarker.ext.servlet.ServletContextHashModel in project ofbiz-framework by apache.
the class ScreenRenderer method populateContextForRequest.
public static void populateContextForRequest(MapStack<String> context, ScreenRenderer screens, HttpServletRequest request, HttpServletResponse response, ServletContext servletContext) {
HttpSession session = request.getSession();
// attribute names to skip for session and application attributes; these are all handled as special cases, duplicating results and causing undesired messages
Set<String> attrNamesToSkip = UtilMisc.toSet("delegator", "dispatcher", "security", "webSiteId", "org.apache.catalina.jsp_classpath");
Map<String, Object> parameterMap = UtilHttp.getCombinedMap(request, attrNamesToSkip);
GenericValue userLogin = (GenericValue) session.getAttribute("userLogin");
populateBasicContext(context, screens, parameterMap, (Delegator) request.getAttribute("delegator"), (LocalDispatcher) request.getAttribute("dispatcher"), (Security) request.getAttribute("security"), UtilHttp.getLocale(request), userLogin);
context.put("autoUserLogin", session.getAttribute("autoUserLogin"));
context.put("person", session.getAttribute("person"));
context.put("partyGroup", session.getAttribute("partyGroup"));
// some things also seem to require this, so here it is:
request.setAttribute("userLogin", userLogin);
// set up the user's time zone
context.put("timeZone", UtilHttp.getTimeZone(request));
// ========== setup values that are specific to OFBiz webapps
VisualTheme visualTheme = UtilHttp.getVisualTheme(request);
if (visualTheme == null) {
String defaultVisualThemeId = EntityUtilProperties.getPropertyValue("general", "VISUAL_THEME", (Delegator) request.getAttribute("delegator"));
visualTheme = ThemeFactory.getVisualThemeFromId(defaultVisualThemeId);
}
context.put("visualTheme", visualTheme);
context.put("modelTheme", visualTheme.getModelTheme());
context.put("request", request);
context.put("response", response);
context.put("session", session);
context.put("application", servletContext);
context.put("webappName", session.getAttribute("_WEBAPP_NAME_"));
if (servletContext != null) {
String rootDir = (String) context.get("rootDir");
String webSiteId = (String) context.get("webSiteId");
String https = (String) context.get("https");
if (UtilValidate.isEmpty(rootDir)) {
rootDir = servletContext.getRealPath("/");
context.put("rootDir", rootDir);
}
if (UtilValidate.isEmpty(webSiteId)) {
webSiteId = WebSiteWorker.getWebSiteId(request);
context.put("webSiteId", webSiteId);
}
if (UtilValidate.isEmpty(https)) {
https = (String) servletContext.getAttribute("https");
context.put("https", https);
}
}
context.put("javaScriptEnabled", Boolean.valueOf(UtilHttp.isJavaScriptEnabled(request)));
// these ones are FreeMarker specific and will only work in FTL templates, mainly here for backward compatibility
context.put("sessionAttributes", new HttpSessionHashModel(session, FreeMarkerWorker.getDefaultOfbizWrapper()));
context.put("requestAttributes", new HttpRequestHashModel(request, FreeMarkerWorker.getDefaultOfbizWrapper()));
TaglibFactory JspTaglibs = new TaglibFactory(servletContext);
context.put("JspTaglibs", JspTaglibs);
context.put("requestParameters", UtilHttp.getParameterMap(request));
ServletContextHashModel ftlServletContext = (ServletContextHashModel) request.getAttribute("ftlServletContext");
context.put("Application", ftlServletContext);
context.put("Request", context.get("requestAttributes"));
// some information from/about the ControlServlet environment
context.put("controlPath", request.getAttribute("_CONTROL_PATH_"));
context.put("contextRoot", request.getAttribute("_CONTEXT_ROOT_"));
context.put("serverRoot", request.getAttribute("_SERVER_ROOT_URL_"));
context.put("checkLoginUrl", LoginWorker.makeLoginUrl(request));
String externalLoginKey = null;
boolean externalLoginKeyEnabled = "true".equals(EntityUtilProperties.getPropertyValue("security", "security.login.externalLoginKey.enabled", "true", (Delegator) request.getAttribute("delegator")));
if (externalLoginKeyEnabled) {
externalLoginKey = ExternalLoginKeysManager.getExternalLoginKey(request);
}
String externalKeyParam = externalLoginKey == null ? "" : "&externalLoginKey=" + externalLoginKey;
context.put("externalLoginKey", externalLoginKey);
context.put("externalKeyParam", externalKeyParam);
// setup message lists
List<String> eventMessageList = UtilGenerics.toList(request.getAttribute("eventMessageList"));
if (eventMessageList == null) {
eventMessageList = new LinkedList<>();
}
List<String> errorMessageList = UtilGenerics.toList(request.getAttribute("errorMessageList"));
if (errorMessageList == null) {
errorMessageList = new LinkedList<>();
}
if (request.getAttribute("_EVENT_MESSAGE_") != null) {
eventMessageList.add(UtilFormatOut.replaceString((String) request.getAttribute("_EVENT_MESSAGE_"), "\n", "<br/>"));
request.removeAttribute("_EVENT_MESSAGE_");
}
List<String> msgList = UtilGenerics.toList(request.getAttribute("_EVENT_MESSAGE_LIST_"));
if (msgList != null) {
eventMessageList.addAll(msgList);
request.removeAttribute("_EVENT_MESSAGE_LIST_");
}
if (request.getAttribute("_ERROR_MESSAGE_") != null) {
errorMessageList.add(UtilFormatOut.replaceString((String) request.getAttribute("_ERROR_MESSAGE_"), "\n", "<br/>"));
request.removeAttribute("_ERROR_MESSAGE_");
}
if (session.getAttribute("_ERROR_MESSAGE_") != null) {
errorMessageList.add(UtilFormatOut.replaceString((String) session.getAttribute("_ERROR_MESSAGE_"), "\n", "<br/>"));
session.removeAttribute("_ERROR_MESSAGE_");
}
msgList = UtilGenerics.toList(request.getAttribute("_ERROR_MESSAGE_LIST_"));
if (msgList != null) {
errorMessageList.addAll(msgList);
request.removeAttribute("_ERROR_MESSAGE_LIST_");
}
context.put("eventMessageList", eventMessageList);
context.put("errorMessageList", errorMessageList);
if (request.getAttribute("serviceValidationException") != null) {
context.put("serviceValidationException", request.getAttribute("serviceValidationException"));
request.removeAttribute("serviceValidationException");
}
// if there was an error message, this is an error
context.put("isError", errorMessageList.size() > 0 ? Boolean.TRUE : Boolean.FALSE);
// if a parameter was passed saying this is an error, it is an error
if ("true".equals(parameterMap.get("isError"))) {
context.put("isError", Boolean.TRUE);
}
// to preserve these values, push the MapStack
context.push();
}
use of freemarker.ext.servlet.ServletContextHashModel in project ofbiz-framework by apache.
the class ControlServlet method doGet.
/**
* @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
*/
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
long requestStartTime = System.currentTimeMillis();
RequestHandler requestHandler = this.getRequestHandler();
HttpSession session = request.getSession();
// setup DEFAULT character encoding and content type, this will be overridden in the RequestHandler for view rendering
String charset = request.getCharacterEncoding();
// setup content type
String contentType = "text/html";
if (UtilValidate.isNotEmpty(charset) && !"none".equals(charset)) {
response.setContentType(contentType + "; charset=" + charset);
response.setCharacterEncoding(charset);
} else {
response.setContentType(contentType);
}
GenericValue userLogin = (GenericValue) session.getAttribute("userLogin");
// set the Entity Engine user info if we have a userLogin
if (userLogin != null) {
GenericDelegator.pushUserIdentifier(userLogin.getString("userLoginId"));
}
// workaraound if we are in the root webapp
String webappName = UtilHttp.getApplicationName(request);
String rname = "";
if (request.getPathInfo() != null) {
rname = request.getPathInfo().substring(1);
}
if (rname.indexOf('/') > 0) {
rname = rname.substring(0, rname.indexOf('/'));
}
UtilTimer timer = null;
if (Debug.timingOn()) {
timer = new UtilTimer();
timer.setLog(true);
timer.timerString("[" + rname + "(Domain:" + request.getScheme() + "://" + request.getServerName() + ")] Request Begun, encoding=[" + charset + "]", module);
}
// Setup the CONTROL_PATH for JSP dispatching.
String contextPath = request.getContextPath();
if (contextPath == null || "/".equals(contextPath)) {
contextPath = "";
}
request.setAttribute("_CONTROL_PATH_", contextPath + request.getServletPath());
if (Debug.verboseOn()) {
Debug.logVerbose("Control Path: " + request.getAttribute("_CONTROL_PATH_"), module);
}
// for convenience, and necessity with event handlers, make security and delegator available in the request:
// try to get it from the session first so that we can have a delegator/dispatcher/security for a certain user if desired
Delegator delegator = null;
String delegatorName = (String) session.getAttribute("delegatorName");
if (UtilValidate.isNotEmpty(delegatorName)) {
delegator = DelegatorFactory.getDelegator(delegatorName);
}
if (delegator == null) {
delegator = (Delegator) getServletContext().getAttribute("delegator");
}
if (delegator == null) {
Debug.logError("[ControlServlet] ERROR: delegator not found in ServletContext", module);
} else {
request.setAttribute("delegator", delegator);
// always put this in the session too so that session events can use the delegator
session.setAttribute("delegatorName", delegator.getDelegatorName());
}
LocalDispatcher dispatcher = (LocalDispatcher) session.getAttribute("dispatcher");
if (dispatcher == null) {
dispatcher = (LocalDispatcher) getServletContext().getAttribute("dispatcher");
}
if (dispatcher == null) {
Debug.logError("[ControlServlet] ERROR: dispatcher not found in ServletContext", module);
}
request.setAttribute("dispatcher", dispatcher);
Security security = (Security) session.getAttribute("security");
if (security == null) {
security = (Security) getServletContext().getAttribute("security");
}
if (security == null) {
Debug.logError("[ControlServlet] ERROR: security not found in ServletContext", module);
}
request.setAttribute("security", security);
VisualTheme visualTheme = UtilHttp.getVisualTheme(request);
if (visualTheme != null) {
UtilHttp.setVisualTheme(request, visualTheme);
}
request.setAttribute("_REQUEST_HANDLER_", requestHandler);
ServletContextHashModel ftlServletContext = new ServletContextHashModel(this, FreeMarkerWorker.getDefaultOfbizWrapper());
request.setAttribute("ftlServletContext", ftlServletContext);
// setup some things that should always be there
UtilHttp.setInitialRequestInfo(request);
VisitHandler.getVisitor(request, response);
// set the Entity Engine user info if we have a userLogin
String visitId = VisitHandler.getVisitId(session);
if (UtilValidate.isNotEmpty(visitId)) {
GenericDelegator.pushSessionIdentifier(visitId);
}
// display details on the servlet objects
if (Debug.verboseOn()) {
logRequestInfo(request);
}
// some containers call filters on EVERY request, even forwarded ones, so let it know that it came from the control servlet
request.setAttribute(ControlFilter.FORWARDED_FROM_SERVLET, Boolean.TRUE);
String errorPage = null;
try {
// the ServerHitBin call for the event is done inside the doRequest method
requestHandler.doRequest(request, response, null, userLogin, delegator);
} catch (RequestHandlerException e) {
Throwable throwable = e.getNested() != null ? e.getNested() : e;
if (throwable instanceof IOException) {
// the connection with the browser is lost and so there is no need to serve the error page; a message is logged to record the event
if (Debug.warningOn())
Debug.logWarning(e, "Communication error with the client while processing the request: " + request.getAttribute("_CONTROL_PATH_") + request.getPathInfo(), module);
if (Debug.verboseOn())
Debug.logVerbose(throwable, module);
} else {
Debug.logError(throwable, "Error in request handler: ", module);
request.setAttribute("_ERROR_MESSAGE_", UtilCodec.getEncoder("html").encode(throwable.toString()));
errorPage = requestHandler.getDefaultErrorPage(request);
}
} catch (RequestHandlerExceptionAllowExternalRequests e) {
errorPage = requestHandler.getDefaultErrorPage(request);
Debug.logInfo("Going to external page: " + request.getPathInfo(), module);
} catch (Exception e) {
Debug.logError(e, "Error in request handler: ", module);
request.setAttribute("_ERROR_MESSAGE_", UtilCodec.getEncoder("html").encode(e.toString()));
errorPage = requestHandler.getDefaultErrorPage(request);
}
if (errorPage != null) {
Debug.logError("An error occurred, going to the errorPage: " + errorPage, module);
RequestDispatcher rd = request.getRequestDispatcher(errorPage);
// use this request parameter to avoid infinite looping on errors in the error page...
if (request.getAttribute("_ERROR_OCCURRED_") == null && rd != null) {
request.setAttribute("_ERROR_OCCURRED_", Boolean.TRUE);
Debug.logError("Including errorPage: " + errorPage, module);
// NOTE DEJ20070727 after having trouble with all of these, try to get the page out and as a last resort just send something back
try {
rd.include(request, response);
} catch (Throwable t) {
Debug.logWarning("Error while trying to send error page using rd.include (will try response.getOutputStream or response.getWriter): " + t.toString(), module);
String errorMessage = "ERROR rendering error page [" + errorPage + "], but here is the error text: " + request.getAttribute("_ERROR_MESSAGE_");
try {
response.getWriter().print(errorMessage);
} catch (Throwable t2) {
try {
int errorToSend = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
Debug.logWarning("Error while trying to write error message using response.getOutputStream or response.getWriter: " + t.toString() + "; sending error code [" + errorToSend + "], and message [" + errorMessage + "]", module);
response.sendError(errorToSend, errorMessage);
} catch (Throwable t3) {
// wow, still bad... just throw an IllegalStateException with the message and let the servlet container handle it
throw new IllegalStateException(errorMessage);
}
}
}
} else {
if (rd == null) {
Debug.logError("Could not get RequestDispatcher for errorPage: " + errorPage, module);
}
String errorMessage = "<html><body>ERROR in error page, (infinite loop or error page not found with name [" + errorPage + "]), but here is the text just in case it helps you: " + request.getAttribute("_ERROR_MESSAGE_") + "</body></html>";
response.getWriter().print(errorMessage);
}
}
// sanity check: make sure we don't have any transactions in place
try {
// roll back current TX first
if (TransactionUtil.isTransactionInPlace()) {
Debug.logWarning("*** NOTICE: ControlServlet finished w/ a transaction in place! Rolling back.", module);
TransactionUtil.rollback();
}
// now resume/rollback any suspended txs
if (TransactionUtil.suspendedTransactionsHeld()) {
int suspended = TransactionUtil.cleanSuspendedTransactions();
Debug.logWarning("Resumed/Rolled Back [" + suspended + "] transactions.", module);
}
} catch (GenericTransactionException e) {
Debug.logWarning(e, module);
}
// run these two again before the ServerHitBin.countRequest call because on a logout this will end up creating a new visit
if (response.isCommitted() && request.getSession(false) == null) {
// response committed and no session, and we can't get a new session, what to do!
// without a session we can't log the hit, etc; so just do nothing; this should NOT happen much!
Debug.logError("Error in ControlServlet output where response isCommitted and there is no session (probably because of a logout); not saving ServerHit/Bin information because there is no session and as the response isCommitted we can't get a new one. The output was successful, but we just can't save ServerHit/Bin info.", module);
} else {
try {
UtilHttp.setInitialRequestInfo(request);
VisitHandler.getVisitor(request, response);
if (requestHandler.trackStats(request)) {
ServerHitBin.countRequest(webappName + "." + rname, request, requestStartTime, System.currentTimeMillis() - requestStartTime, userLogin);
}
} catch (Throwable t) {
Debug.logError(t, "Error in ControlServlet saving ServerHit/Bin information; the output was successful, but can't save this tracking information. The error was: " + t.toString(), module);
}
}
if (Debug.timingOn())
timer.timerString("[" + rname + "(Domain:" + request.getScheme() + "://" + request.getServerName() + ")] Request Done", module);
// sanity check 2: make sure there are no user or session infos in the delegator, ie clear the thread
GenericDelegator.clearUserIdentifierStack();
GenericDelegator.clearSessionIdentifierStack();
}
Aggregations