Search in sources :

Example 16 with VisualTheme

use of org.apache.ofbiz.widget.renderer.VisualTheme in project ofbiz-framework by apache.

the class FoPrintServerEvents method getXslFo.

public static byte[] getXslFo(DispatchContext dctx, String screen, Map<String, Object> parameters) throws GeneralException {
    // run as the system user
    VisualTheme visualTheme = (VisualTheme) parameters.get("visualTheme");
    GenericValue system = null;
    try {
        system = dctx.getDelegator().findOne("UserLogin", false, "userLoginId", "system");
    } catch (GenericEntityException e) {
        throw new GeneralException(e.getMessage(), e);
    }
    parameters.put("userLogin", system);
    if (!parameters.containsKey("locale")) {
        parameters.put("locale", Locale.getDefault());
    }
    // render and obtain the XSL-FO
    Writer writer = new StringWriter();
    try {
        ScreenStringRenderer screenStringRenderer = new MacroScreenRenderer(visualTheme.getModelTheme().getType("screen"), visualTheme.getModelTheme().getScreenRendererLocation("screen"));
        ScreenRenderer screens = new ScreenRenderer(writer, null, screenStringRenderer);
        screens.populateContextForService(dctx, parameters);
        screens.render(screen);
    } catch (Throwable t) {
        throw new GeneralException("Problems rendering FOP XSL-FO", t);
    }
    return writer.toString().getBytes();
}
Also used : GenericValue(org.apache.ofbiz.entity.GenericValue) GeneralException(org.apache.ofbiz.base.util.GeneralException) StringWriter(java.io.StringWriter) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) MacroScreenRenderer(org.apache.ofbiz.widget.renderer.macro.MacroScreenRenderer) ScreenRenderer(org.apache.ofbiz.widget.renderer.ScreenRenderer) VisualTheme(org.apache.ofbiz.widget.renderer.VisualTheme) StringWriter(java.io.StringWriter) Writer(java.io.Writer) ScreenStringRenderer(org.apache.ofbiz.widget.renderer.ScreenStringRenderer) MacroScreenRenderer(org.apache.ofbiz.widget.renderer.macro.MacroScreenRenderer)

Example 17 with VisualTheme

use of org.apache.ofbiz.widget.renderer.VisualTheme 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();
}
Also used : GenericValue(org.apache.ofbiz.entity.GenericValue) LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) HttpSession(javax.servlet.http.HttpSession) UtilTimer(org.apache.ofbiz.base.util.UtilTimer) IOException(java.io.IOException) Security(org.apache.ofbiz.security.Security) ServletException(javax.servlet.ServletException) IOException(java.io.IOException) GenericTransactionException(org.apache.ofbiz.entity.transaction.GenericTransactionException) RequestDispatcher(javax.servlet.RequestDispatcher) Delegator(org.apache.ofbiz.entity.Delegator) GenericDelegator(org.apache.ofbiz.entity.GenericDelegator) ServletContextHashModel(freemarker.ext.servlet.ServletContextHashModel) GenericTransactionException(org.apache.ofbiz.entity.transaction.GenericTransactionException) VisualTheme(org.apache.ofbiz.widget.renderer.VisualTheme)

Example 18 with VisualTheme

use of org.apache.ofbiz.widget.renderer.VisualTheme in project ofbiz-framework by apache.

the class ThemeFactory method resolveVisualTheme.

/**
 * Resolve the enabled VisualTheme with this find order
 * If a user is logged
 * 1. Check if present en session with key "visualTheme"
 * 2. Check from user preference
 * If user isn't logged or visualTheme not find with logged user
 * 3. Check if visualThemeId has been set on the webapp attribute
 * 4. Check the general.properties VISUAL_THEME
 * 5. return COMMON
 * @param request
 * @return
 */
public static VisualTheme resolveVisualTheme(HttpServletRequest request) {
    String visualThemeId = null;
    if (request != null) {
        HttpSession session = request.getSession();
        GenericValue userLogin = (GenericValue) session.getAttribute("userLogin");
        // search on request only if a userLogin is present on session (otherwise this implied that the user isn't identify so wait
        if (userLogin != null) {
            VisualTheme visualTheme = (VisualTheme) session.getAttribute("visualTheme");
            if (visualTheme != null) {
                return visualTheme;
            }
            // resolve on user pref
            LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
            if (dispatcher != null) {
                try {
                    Map<String, Object> userPreferencesResult = dispatcher.runSync("getUserPreference", UtilMisc.toMap("userLogin", userLogin, "userPrefTypeId", "VISUAL_THEME"));
                    visualThemeId = (String) userPreferencesResult.get("userPrefValue");
                } catch (GenericServiceException e) {
                    Debug.logError("Impossible to resolve the theme from user prefrence for " + userLogin.get("userLoginId"), module);
                }
            }
        }
        // resolve from webapp
        if (visualThemeId == null) {
            ServletContext servletContext = request.getServletContext();
            visualThemeId = servletContext.getInitParameter("visualThemeId");
        }
    }
    // resolve from general properties
    if (visualThemeId == null) {
        visualThemeId = UtilProperties.getPropertyValue("general", "VISUAL_THEME", "COMMON");
    }
    return getVisualThemeFromId(visualThemeId);
}
Also used : GenericValue(org.apache.ofbiz.entity.GenericValue) LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) HttpSession(javax.servlet.http.HttpSession) ServletContext(javax.servlet.ServletContext) VisualTheme(org.apache.ofbiz.widget.renderer.VisualTheme) GenericServiceException(org.apache.ofbiz.service.GenericServiceException)

Aggregations

VisualTheme (org.apache.ofbiz.widget.renderer.VisualTheme)18 TemplateException (freemarker.template.TemplateException)11 IOException (java.io.IOException)10 GeneralException (org.apache.ofbiz.base.util.GeneralException)9 ModelTheme (org.apache.ofbiz.widget.model.ModelTheme)9 ScreenRenderer (org.apache.ofbiz.widget.renderer.ScreenRenderer)9 ScreenStringRenderer (org.apache.ofbiz.widget.renderer.ScreenStringRenderer)9 StringWriter (java.io.StringWriter)8 Writer (java.io.Writer)8 MacroScreenRenderer (org.apache.ofbiz.widget.renderer.macro.MacroScreenRenderer)8 ParserConfigurationException (javax.xml.parsers.ParserConfigurationException)7 SAXException (org.xml.sax.SAXException)7 Delegator (org.apache.ofbiz.entity.Delegator)6 Locale (java.util.Locale)5 GenericValue (org.apache.ofbiz.entity.GenericValue)5 LocalDispatcher (org.apache.ofbiz.service.LocalDispatcher)5 ByteArrayOutputStream (java.io.ByteArrayOutputStream)4 StringReader (java.io.StringReader)4 HashMap (java.util.HashMap)4 Map (java.util.Map)4