Example usage for javax.servlet.jsp.jstl.core Config set

List of usage examples for javax.servlet.jsp.jstl.core Config set

Introduction

In this page you can find the example usage for javax.servlet.jsp.jstl.core Config set.

Prototype

public static void set(ServletContext context, String name, Object value) 

Source Link

Document

Sets the value of a configuration variable in the "application" scope.

Usage

From source file:org.apache.shale.tiles.TilesViewHandler.java

/**
 * executePageToBuildView// www  .j  av  a  2s  . c  om
 *
 * added by wjb oct 2006 per SunRI and sdoglesby
 *
 */
private boolean executePageToBuildView(FacesContext context, UIViewRoot viewToExecute, ComponentDefinition tile)
        throws IOException {
    System.out.println("in executePageToBuildView ...");
    if (null == context) {
        String message = MessageUtils.getExceptionMessageString(MessageUtils.NULL_PARAMETERS_ERROR_MESSAGE_ID,
                "context");
        throw new NullPointerException(message);
    }
    if (null == viewToExecute) {
        String message = MessageUtils.getExceptionMessageString(MessageUtils.NULL_PARAMETERS_ERROR_MESSAGE_ID,
                "viewToExecute");
        throw new NullPointerException(message);
    }

    String mapping = Util.getFacesMapping(context);

    String requestURI = updateRequestURI(tile.getPath(), mapping);
    if (mapping.equals(requestURI)) {
        // The request was to the FacesServlet only - no path info
        // on some containers this causes a recursion in the
        // RequestDispatcher and the request appears to hang.
        // If this is detected, return status 404
        HttpServletResponse response = (HttpServletResponse) context.getExternalContext().getResponse();
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return true;
    }

    ExternalContext extContext = context.getExternalContext();

    // update the JSTL locale attribute in request scope so that JSTL
    // picks up the locale from viewRoot. This attribute must be updated
    // before the JSTL setBundle tag is called because that is when the
    // new LocalizationContext object is created based on the locale.
    // PENDING: this only works for servlet based requests
    if (extContext.getRequest() instanceof ServletRequest) {
        Config.set((ServletRequest) extContext.getRequest(), Config.FMT_LOCALE,
                context.getViewRoot().getLocale());
    }

    // save the original response
    Object originalResponse = extContext.getResponse();

    // replace the response with our wrapper
    ViewHandlerResponseWrapper wrapped = new ViewHandlerResponseWrapper(
            (HttpServletResponse) extContext.getResponse());
    extContext.setResponse(wrapped);

    // build the view by executing the page
    extContext.dispatch(requestURI);

    // replace the original response
    extContext.setResponse(originalResponse);
    // Follow the JSTL 1.2 spec, section 7.4,
    // on handling status codes on a forward
    if (wrapped.getStatus() < 200 || wrapped.getStatus() > 299) {
        // flush the contents of the wrapper to the response
        // this is necessary as the user may be using a custom
        // error page - this content should be propagated
        wrapped.flushContentToWrappedResponse();
        return true;
    }

    // Put the AFTER_VIEW_CONTENT into request scope
    // temporarily
    if (wrapped.isBytes()) {
        extContext.getRequestMap().put(AFTER_VIEW_CONTENT, wrapped.getBytes());
    } else if (wrapped.isChars()) {
        extContext.getRequestMap().put(AFTER_VIEW_CONTENT, wrapped.getChars());
    }

    return false;

}

From source file:org.dspace.app.webui.util.UIUtil.java

/**
 * Obtain a new context object. If a context object has already been created
 * for this HTTP request, it is re-used, otherwise it is created. If a user
 * has authenticated with the system, the current user of the context is set
 * appropriately./*w w w.ja v  a  2s .c  o  m*/
 * 
 * @param request
 *            the HTTP request
 * 
 * @return a context object
 */
public static Context obtainContext(HttpServletRequest request) throws SQLException {

    //Set encoding to UTF-8, if not set yet
    //This avoids problems of using the HttpServletRequest
    //in the getSpecialGroups() for an AuthenticationMethod,  
    //which causes the HttpServletRequest to default to 
    //non-UTF-8 encoding.
    try {
        if (request.getCharacterEncoding() == null) {
            request.setCharacterEncoding(Constants.DEFAULT_ENCODING);
        }
    } catch (Exception e) {
        log.error("Unable to set encoding to UTF-8.", e);
    }

    Context c = (Context) request.getAttribute("dspace.context");

    if (c == null) {
        // No context for this request yet
        c = new Context();
        HttpSession session = request.getSession();

        // See if a user has authentication
        Integer userID = (Integer) session.getAttribute("dspace.current.user.id");

        if (userID != null) {
            String remAddr = (String) session.getAttribute("dspace.current.remote.addr");
            if (remAddr != null && remAddr.equals(request.getRemoteAddr())) {
                EPerson e = EPerson.find(c, userID.intValue());

                Authenticate.loggedIn(c, request, e);
            } else {
                log.warn("POSSIBLE HIJACKED SESSION: request from " + request.getRemoteAddr()
                        + " does not match original " + "session address: " + remAddr
                        + ". Authentication rejected.");
            }
        }

        // Set any special groups - invoke the authentication mgr.
        int[] groupIDs = AuthenticationManager.getSpecialGroups(c, request);

        for (int i = 0; i < groupIDs.length; i++) {
            c.setSpecialGroup(groupIDs[i]);
            log.debug("Adding Special Group id=" + String.valueOf(groupIDs[i]));
        }

        // Set the session ID and IP address
        String ip = request.getRemoteAddr();
        if (useProxies == null) {
            useProxies = ConfigurationManager.getBooleanProperty("useProxies", false);
        }
        if (useProxies && request.getHeader("X-Forwarded-For") != null) {
            /* This header is a comma delimited list */
            for (String xfip : request.getHeader("X-Forwarded-For").split(",")) {
                if (!request.getHeader("X-Forwarded-For").contains(ip)) {
                    ip = xfip.trim();
                }
            }
        }
        c.setExtraLogInfo("session_id=" + request.getSession().getId() + ":ip_addr=" + ip);

        // Store the context in the request
        request.setAttribute("dspace.context", c);
    }

    // Set the locale to be used
    Locale sessionLocale = getSessionLocale(request);
    Config.set(request.getSession(), Config.FMT_LOCALE, sessionLocale);
    c.setCurrentLocale(sessionLocale);

    return c;
}

From source file:org.jahia.bin.JahiaAdministration.java

/**
 * This method is used like a dispatcher for user requests.
 *
 * @param request  Servlet request.//from www. j  a v a2s . c  o  m
 * @param response Servlet response.
 * @param session  Servlet session for the current user.
 */
private void userRequestDispatcher(final HttpServletRequest request, final HttpServletResponse response,
        final HttpSession session) throws JahiaException, IOException, ServletException {
    String op = request.getParameter("do");
    if (op == null)
        op = "";
    final String operation = op;

    ParamBean jParams = initAdminJahiaData(request, response, session);
    final JahiaUser user = jParams.getUser();
    final JahiaSite site = jParams.getSite();

    try {
        Boolean accessGranted = (Boolean) session.getAttribute(CLASS_NAME + "accessGranted");
        if (accessGranted == null) {
            accessGranted = Boolean.FALSE;
        }

        if (accessGranted) {
            Locale uiLocale = (Locale) request.getSession().getAttribute(ProcessingContext.SESSION_UI_LOCALE);
            if (request.getParameter("switchUiLocale") != null) {
                uiLocale = LanguageCodeConverters.languageCodeToLocale(request.getParameter("switchUiLocale"));
                request.getSession().setAttribute(ProcessingContext.SESSION_UI_LOCALE, uiLocale);
                user.setProperty("preferredLanguage", uiLocale.toString());
            }

            Config.set(request, Config.FMT_LOCALIZATION_CONTEXT, new LocalizationContext(
                    new JahiaResourceBundle(uiLocale, site.getTemplatePackageName()), uiLocale));

            AdministrationModulesRegistry modulesRegistry = (AdministrationModulesRegistry) SpringContextSingleton
                    .getInstance().getContext().getBean("administrationModulesRegistry");
            AdministrationModule currentModule = modulesRegistry.getServerAdministrationModule(operation);
            if (currentModule != null) {
                if (hasSitePermission(currentModule.getPermissionName(), site.getSiteKey())
                        || hasServerPermission(currentModule.getPermissionName())) {
                    session.setAttribute(CLASS_NAME + "configJahia", Boolean.TRUE);
                    /** todo clean up this hardcoded mess. Is it even used anymore ? */
                    if ("sharecomponents".equals(operation) && user.isRoot()) {
                        request.setAttribute("showAllComponents", Boolean.TRUE);
                    }

                    currentModule.service(request, response);
                } else if ("sites".equals(operation)
                        && (session.getAttribute(JahiaAdministration.CLASS_NAME + "redirectToJahia") != null)) {
                    session.setAttribute(CLASS_NAME + "configJahia", Boolean.TRUE);
                    currentModule.service(request, response);
                }
            } else {
                currentModule = modulesRegistry.getSiteAdministrationModule(operation);
                if (currentModule != null) {
                    if (hasSitePermission(currentModule.getPermissionName(), site.getSiteKey())) {
                        session.setAttribute(CLASS_NAME + "configJahia", Boolean.FALSE);
                        if ("search".equals(operation)) {
                            // Use response wrapper to ensure correct handling of Application fields output to the response
                            // @todo is this still necessary with Pluto wrapper in effect ?
                            currentModule.service(new ServletIncludeRequestWrapper(request),
                                    new ServletIncludeResponseWrapper(response, true,
                                            SettingsBean.getInstance().getCharacterEncoding()));
                        } else {
                            currentModule.service(request, response);
                        }
                    }
                }
            }

            if ("switch".equals(operation)) {
                // operation : switch management mode (server, sites)
                switchModeAction(request, response, session);
            } else if ("change".equals(operation)) {
                // operation : change site id to manage
                session.setAttribute(CLASS_NAME + "configJahia", Boolean.FALSE);
                changeSite(request, response, session);
            } else {
                if (currentModule == null) {
                    displayMenu(request, response, session);
                }
            }

            // the user don't currently have a granted access...
        } else if (isValidLoginSession(session)) {
            displayMenu(request, response, session);
        } else {
            logger.debug("session login not valid.");
            if (JahiaUserManagerService
                    .isGuest((JahiaUser) session.getAttribute(ProcessingContext.SESSION_USER))) {
                displayLogin(request, response, session);
            } else {
                throw new JahiaForbiddenAccessException();
            }
        }
    } catch (Exception e) {
        if (e instanceof JahiaForbiddenAccessException) {
            throw (JahiaForbiddenAccessException) e;
        }
        logger.error("Error during " + operation + " operation", e);
        if (isValidLoginSession(session)) {
            displayMenu(request, response, session);
        } else {
            if (JahiaUserManagerService
                    .isGuest((JahiaUser) session.getAttribute(ProcessingContext.SESSION_USER))) {
                displayLogin(request, response, session);
            } else {
                throw new JahiaForbiddenAccessException();
            }
        }
    }
}

From source file:org.jahia.bin.listeners.JahiaContextLoaderListener.java

@SuppressWarnings("unchecked")
public static void endContextInitialized() {
    try {/*from www .j  ava  2 s  . c  o m*/
        logger.info("Finishing context initialization phase");

        // do initialization of all services, implementing JahiaAfterInitializationService
        initJahiaAfterInitializationServices();

        // register listeners after the portal is started
        ApplicationsManagerServiceImpl.getInstance().registerListeners();

        // set fallback locale
        Config.set(servletContext, Config.FMT_FALLBACK_LOCALE,
                (SettingsBean.getInstance().getDefaultLanguageCode() != null)
                        ? SettingsBean.getInstance().getDefaultLanguageCode()
                        : Locale.ENGLISH.getLanguage());

        jahiaContextListenersConfiguration = (Map<String, Object>) ContextLoader
                .getCurrentWebApplicationContext().getBean("jahiaContextListenersConfiguration");
        if (isEventInterceptorActivated("interceptServletContextListenerEvents")) {
            SpringContextSingleton.getInstance()
                    .publishEvent(new ServletContextInitializedEvent(getServletContext()));
        }
        contextInitialized = true;

        // execute patches after the complete initialization
        if (SettingsBean.getInstance().isProcessingServer()) {
            GroovyPatcher.executeScripts(servletContext, "contextInitialized");
        } else {
            // we leave the possibility to provide Groovy scripts for non-processing servers
            GroovyPatcher.executeScripts(servletContext, "nonProcessingServer");
        }
        logger.info("Context initialization phase finished");
    } catch (JahiaException e) {
        running = false;
        logger.error(e.getMessage(), e);
        throw new JahiaRuntimeException(e);
    } catch (RuntimeException e) {
        running = false;
        throw e;
    } finally {
        JCRSessionFactory.getInstance().closeAllSessions();
    }
}

From source file:org.jahia.params.ParamBean.java

/**
 * Change the current Locale Reinit the locales list and the entry load request too !
 *
 * @param locale//from  w  w w.  ja  v a  2  s  .  co m
 */
public void changeLanguage(final Locale locale) throws JahiaException {
    super.changeLanguage(locale);
    // added by PAP: for Struts and JSTL applications
    this.getSession().setAttribute("org.apache.struts.action.LOCALE", locale);
    Config.set(this.getSession(), Config.FMT_LOCALE, locale);

}

From source file:org.tangram.view.Utils.java

/**
 * Take the primary browser language from the request as input for JST fmt tag library.
 *
 * Only consideres the first language in the list taken from the clients reuqest.
 *
 * @param request request to read accept-language header from and set request attribute to.
 *//*from   w w w  .  java 2s. c  o m*/
public static void setPrimaryBrowserLanguageForJstl(HttpServletRequest request) {
    String acceptLanguageHeader = request.getHeader("Accept-Language");
    if (acceptLanguageHeader == null) {
        return;
    } // if
    String[] acceptLanguages = acceptLanguageHeader.split(",");
    if (acceptLanguages.length > 0) {
        String[] acceptLanguage = acceptLanguages[0].split(";");
        if (acceptLanguage.length > 0) {
            String language[] = acceptLanguage[0].split("-");
            if (language.length > 0) {
                final String localeCode = language[0];
                LOG.info("setPrimaryBrowserLanguageForJstl() setting request language {}", localeCode);
                Config.set(request, Config.FMT_LOCALE, new Locale(localeCode));
            } // if
        } // if
    } // if
}