Example usage for javax.servlet ServletContext setAttribute

List of usage examples for javax.servlet ServletContext setAttribute

Introduction

In this page you can find the example usage for javax.servlet ServletContext setAttribute.

Prototype

public void setAttribute(String name, Object object);

Source Link

Document

Binds an object to a given attribute name in this ServletContext.

Usage

From source file:net.naijatek.myalumni.modules.admin.presentation.action.MaintainSystemModuleAction.java

public ActionForward updateOrgInfo(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    logger.debug("in updateOrgInfo...");
    if (!isTokenValid(request)) {
        return mapping.findForward(BaseConstants.FWD_INVALID_TOKEN);
    }//from  ww w.ja  va2  s.  c  o m
    ActionMessages msgs = new ActionMessages();
    SystemConfigForm orgInfoForm = (SystemConfigForm) form;
    SystemConfigVO orgInfoVO = new SystemConfigVO();
    BeanUtils.copyProperties(orgInfoVO, orgInfoForm);

    orgInfoVO.setLastModifiedBy(getLastModifiedBy(request));

    systemConfigService.updateOrgInfo(orgInfoVO);
    msgs.add(BaseConstants.INFO_KEY, new ActionMessage("message.record.updated"));
    saveMessages(request, msgs);
    resetToken(request);
    ServletContext sCtx = request.getSession().getServletContext();
    sCtx.setAttribute(BaseConstants.ORGANIZATION_NAME, orgInfoVO.getOrganizationName());
    sCtx.setAttribute(BaseConstants.ORGANIZATION_SHORT_NAME, orgInfoVO.getOrganizationShortName());
    sCtx.setAttribute(BaseConstants.ORG_EMAIL, orgInfoVO.getOrgEmail());
    return mapping.findForward(BaseConstants.FWD_SUCCESS);
}

From source file:net.naijatek.myalumni.modules.admin.presentation.action.MaintainSystemModuleAction.java

public ActionForward removeLogo(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    logger.debug("in removeLogo...");
    if (!adminSecurityCheck(request)) {
        return mapping.findForward(BaseConstants.FWD_ADMIN_LOGIN);
    }/*ww w .j  av a 2  s .  c  o  m*/

    //ActionMessages msgs = new ActionMessages();
    String logoFileName = new String();
    SystemConfigVO systemConfigVO = new SystemConfigVO();
    systemConfigVO = systemConfigService.getSystemConfig();
    logoFileName = systemConfigVO.getLogoFileName();
    systemConfigVO.setLogoFileName(null);
    systemConfigService.uploadLogo(systemConfigVO);

    //delete actual logo from file system
    String logoDir = getSysProp().getValue("LOGO.FILEPATH");
    File f = new File(logoDir + logoFileName);
    if (!f.isDirectory() && f.exists())
        f.delete();

    ServletContext sCtx = request.getSession().getServletContext();
    sCtx.setAttribute(BaseConstants.LOGO_NAME, null);
    return mapping.findForward(BaseConstants.FWD_SUCCESS);
}

From source file:org.jbpm.bpel.integration.server.IntegrationConfigurator.java

public void contextInitialized(ServletContextEvent event) {
    ServletContext servletContext = event.getServletContext();

    String configResource = servletContext.getInitParameter(JBPM_CONFIG_RESOURCE_PARAM);
    JbpmConfiguration jbpmConfiguration = JbpmConfiguration.getInstance(configResource);

    JbpmContext jbpmContext = jbpmConfiguration.createJbpmContext();
    try {/*from ww w .jav  a  2s.c o  m*/
        // read the app descriptor from a classpath resource
        DeploymentDescriptor deploymentDescriptor = DeploymentDescriptor.readDeploymentDescriptor(jbpmContext);
        // obtain the integration control for the process definition referenced in the descriptor
        BpelProcessDefinition processDefinition = deploymentDescriptor.findProcessDefinition(jbpmContext);
        JmsIntegrationServiceFactory integrationServiceFactory = JmsIntegrationServiceFactory
                .getConfigurationInstance(jbpmConfiguration);
        IntegrationControl integrationControl = integrationServiceFactory
                .getIntegrationControl(processDefinition);

        // make app descriptor available to message activities
        integrationControl.setDeploymentDescriptor(deploymentDescriptor);
        // start receiving requests
        integrationControl.enableInboundMessageActivities(jbpmContext);

        // make integration control available to jax-rpc handlers
        servletContext.setAttribute(SoapHandler.INTEGRATION_CONTROL_ATTR, integrationControl);

        log.info("message reception enabled for process: " + deploymentDescriptor.getName());
    } catch (RuntimeException e) {
        jbpmContext.setRollbackOnly();
        throw e;
    } catch (NamingException e) {
        jbpmContext.setRollbackOnly();
        throw new BpelException("could not start bpel application", e);
    } catch (JMSException e) {
        jbpmContext.setRollbackOnly();
        throw new BpelException("could not start bpel application", e);
    } finally {
        jbpmContext.close();
    }
}

From source file:org.glom.web.server.OnlineGlomServlet.java

protected ConfiguredDocumentSet getConfiguredDocumentSet() {
    //See if there is already a shared documentSet:
    final ServletConfig config = this.getServletConfig();
    if (config == null) {
        Log.error("getServletConfig() return null");
        return null;
    }//from  w  w w  . j av  a2  s.  c  o m

    final ServletContext context = config.getServletContext();
    if (context == null) {
        Log.error("getServletContext() return null");
        return null;
    }

    //Use the existing shared document set, if any:
    final Object object = context.getAttribute(CONFIGURED_DOCUMENT_SET);
    if ((object != null) && !(object instanceof ConfiguredDocumentSet)) {
        Log.error("The configuredDocumentSet attribute is not of the expected type.");
        return null;
    }

    ConfiguredDocumentSet configuredDocumentSet = (ConfiguredDocumentSet) object;
    if (configuredDocumentSet != null) {
        return configuredDocumentSet;
    }

    //Create the shared document set:
    //TODO: Possible race condition between checking and creating+setting:
    configuredDocumentSet = new ConfiguredDocumentSet();
    try {
        configuredDocumentSet.readConfiguration();
    } catch (ServletException e) {
        Log.error("Configuration error", e);
        return null;
    }

    //Store it in the Servlet Context,
    //so it is available to all servlets:
    context.setAttribute(CONFIGURED_DOCUMENT_SET, configuredDocumentSet);

    return configuredDocumentSet;
}

From source file:net.naijatek.myalumni.modules.admin.presentation.action.MaintainSystemModuleAction.java

public ActionForward uploadLogo(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    logger.debug("in uploadLogo...");

    if (!adminSecurityCheck(request)) {
        return mapping.findForward(BaseConstants.FWD_ADMIN_LOGIN);
    }//from ww w . ja  v  a 2  s.  co  m
    SystemConfigForm systemConfigForm = (SystemConfigForm) form;
    String fileAllowedTypes = SystemConfigConstants.CONTENT_TYPE;
    int maxFileSize = SystemConfigConstants.LOGO_MAX_SIZE;
    ActionMessages msgs = new ActionMessages();
    FormFile formFile = systemConfigForm.getLogoUpload();
    int height = SystemConfigConstants.LOGO_HEIGHT;
    int width = SystemConfigConstants.LOGO_WIDTH;
    msgs = validateUploadFile(request, formFile, fileAllowedTypes, maxFileSize, true, height, false, width);

    if (msgs.isEmpty()) {
        // upload the file and update database
        try {
            String logoDir = getSysProp().getValue("LOGO.FILEPATH");
            uploadFromLocalDrive(formFile, formFile.getFileName(), logoDir);
        } catch (Exception e) {
            msgs.add(BaseConstants.WARN_KEY, new ActionMessage("error.cantupload"));
        }

        SystemConfigVO systemConfigVO = systemConfigService.getSystemConfig();
        systemConfigVO.setLogoFileName(formFile.getFileName());
        systemConfigService.uploadLogo(systemConfigVO);
        ServletContext sCtx = request.getSession().getServletContext();
        sCtx.setAttribute(BaseConstants.LOGO_NAME, systemConfigVO.getLogoFileName());
    }

    saveMessages(request, msgs);
    return mapping.findForward(BaseConstants.FWD_SUCCESS);
}

From source file:com.ibm.jaggr.core.impl.AbstractAggregatorImpl.java

@Override
public void init(ServletConfig servletConfig) throws ServletException {
    final String sourceMethod = "init"; //$NON-NLS-1$
    boolean isTraceLogging = log.isLoggable(Level.FINER);
    if (isTraceLogging) {
        log.entering(AbstractAggregatorImpl.class.getName(), sourceMethod, new Object[] { servletConfig });
    }/*from   w w  w .  ja  v a2 s . c  o m*/
    super.init(servletConfig);

    final ServletContext context = servletConfig.getServletContext();

    // Set servlet context attributes for access though the request
    context.setAttribute(IAggregator.AGGREGATOR_REQATTRNAME, this);
    if (isTraceLogging) {
        log.exiting(AbstractAggregatorImpl.class.getName(), sourceMethod);
    }
}

From source file:org.red5.server.tomcat.TomcatLoader.java

/**
 * Initialization./*from   ww  w . j  ava  2 s. c o  m*/
 */
public void init() {
    log.info("Loading tomcat context");

    //get a reference to the current threads classloader
    final ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader();

    // root location for servlet container
    String serverRoot = System.getProperty("red5.root");
    log.info("Server root: {}", serverRoot);
    String confRoot = System.getProperty("red5.config_root");
    log.info("Config root: {}", confRoot);

    // create one embedded (server) and use it everywhere
    embedded = new Embedded();
    embedded.createLoader(originalClassLoader);
    embedded.setCatalinaBase(serverRoot);
    embedded.setCatalinaHome(serverRoot);
    embedded.setName(serviceEngineName);
    log.trace("Classloader for embedded: {} TCL: {}", Embedded.class.getClassLoader(), originalClassLoader);

    engine = embedded.createEngine();
    engine.setDefaultHost(host.getName());
    engine.setName(serviceEngineName);

    if (webappFolder == null) {
        // Use default webapps directory
        webappFolder = FileUtil.formatPath(System.getProperty("red5.root"), "/webapps");
    }
    System.setProperty("red5.webapp.root", webappFolder);
    log.info("Application root: {}", webappFolder);

    // scan for additional webapp contexts

    // Root applications directory
    File appDirBase = new File(webappFolder);
    // Subdirs of root apps dir
    File[] dirs = appDirBase.listFiles(new DirectoryFilter());
    // Search for additional context files
    for (File dir : dirs) {
        String dirName = '/' + dir.getName();
        // check to see if the directory is already mapped
        if (null == host.findChild(dirName)) {
            String webappContextDir = FileUtil.formatPath(appDirBase.getAbsolutePath(), dirName);
            log.debug("Webapp context directory (full path): {}", webappContextDir);
            Context ctx = null;
            if ("/root".equals(dirName) || "/root".equalsIgnoreCase(dirName)) {
                log.trace("Adding ROOT context");
                ctx = addContext("/", webappContextDir);
            } else {
                log.trace("Adding context from directory scan: {}", dirName);
                ctx = addContext(dirName, webappContextDir);
            }
            log.trace("Context: {}", ctx);

            //see if the application requests php support
            String enablePhp = ctx.findParameter("enable-php");
            //if its null try to read directly
            if (enablePhp == null) {
                File webxml = new File(webappContextDir + "/WEB-INF/", "web.xml");
                if (webxml.exists() && webxml.canRead()) {
                    try {
                        DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
                        DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
                        Document doc = docBuilder.parse(webxml);
                        // normalize text representation
                        doc.getDocumentElement().normalize();
                        log.trace("Root element of the doc is {}", doc.getDocumentElement().getNodeName());
                        NodeList listOfElements = doc.getElementsByTagName("context-param");
                        int totalElements = listOfElements.getLength();
                        log.trace("Total no of elements: {}", totalElements);
                        for (int s = 0; s < totalElements; s++) {
                            Node fstNode = listOfElements.item(s);
                            if (fstNode.getNodeType() == Node.ELEMENT_NODE) {
                                Element fstElmnt = (Element) fstNode;
                                NodeList fstNmElmntLst = fstElmnt.getElementsByTagName("param-name");
                                Element fstNmElmnt = (Element) fstNmElmntLst.item(0);
                                NodeList fstNm = fstNmElmnt.getChildNodes();
                                String pName = (fstNm.item(0)).getNodeValue();
                                log.trace("Param name: {}", pName);
                                if ("enable-php".equals(pName)) {
                                    NodeList lstNmElmntLst = fstElmnt.getElementsByTagName("param-value");
                                    Element lstNmElmnt = (Element) lstNmElmntLst.item(0);
                                    NodeList lstNm = lstNmElmnt.getChildNodes();
                                    String pValue = (lstNm.item(0)).getNodeValue();
                                    log.trace("Param value: {}", pValue);
                                    enablePhp = pValue;
                                    //
                                    break;
                                }
                            }
                        }
                    } catch (Exception e) {
                        log.warn("Error reading web.xml", e);
                    }
                }
                webxml = null;
            }
            log.debug("Enable php: {}", enablePhp);
            if ("true".equals(enablePhp)) {
                log.info("Adding PHP (Quercus) servlet for context: {}", ctx.getName());
                // add servlet wrapper
                StandardWrapper wrapper = (StandardWrapper) ctx.createWrapper();
                wrapper.setServletName("QuercusServlet");
                wrapper.setServletClass("com.caucho.quercus.servlet.QuercusServlet");
                log.debug("Wrapper: {}", wrapper);
                ctx.addChild(wrapper);
                // add servlet mappings
                ctx.addServletMapping("*.php", "QuercusServlet");
            }

            webappContextDir = null;
        }
    }
    appDirBase = null;
    dirs = null;

    // Dump context list
    if (log.isDebugEnabled()) {
        for (Container cont : host.findChildren()) {
            log.debug("Context child name: {}", cont.getName());
        }
    }

    // Set a realm
    if (realm == null) {
        realm = new MemoryRealm();
    }
    embedded.setRealm(realm);

    // use Tomcat jndi or not
    if (System.getProperty("catalina.useNaming") != null) {
        embedded.setUseNaming(Boolean.valueOf(System.getProperty("catalina.useNaming")));
    }

    // add the valves to the host
    for (Valve valve : valves) {
        log.debug("Adding host valve: {}", valve);
        ((StandardHost) host).addValve(valve);
    }

    // baseHost = embedded.createHost(hostName, appRoot);
    engine.addChild(host);

    // add any additional hosts
    if (hosts != null && !hosts.isEmpty()) {
        // grab current contexts from base host
        Container[] currentContexts = host.findChildren();
        log.info("Adding {} additional hosts", hosts.size());
        for (Host h : hosts) {
            log.debug("Host - name: {} appBase: {} info: {}",
                    new Object[] { h.getName(), h.getAppBase(), h.getInfo() });
            //add the contexts to each host
            for (Container cont : currentContexts) {
                Context c = (Context) cont;
                addContext(c.getPath(), c.getDocBase(), h);
            }
            //add the host to the engine
            engine.addChild(h);
        }
    }

    // Add new Engine to set of Engine for embedded server
    embedded.addEngine(engine);

    // set connection properties
    for (String key : connectionProperties.keySet()) {
        log.debug("Setting connection property: {} = {}", key, connectionProperties.get(key));
        if (connectors == null || connectors.isEmpty()) {
            connector.setProperty(key, connectionProperties.get(key));
        } else {
            for (Connector ctr : connectors) {
                ctr.setProperty(key, connectionProperties.get(key));
            }
        }
    }

    // set the bind address
    if (address == null) {
        //bind locally
        address = InetSocketAddress.createUnresolved("127.0.0.1", connector.getPort()).getAddress();
    }
    // apply the bind address
    ProtocolHandler handler = connector.getProtocolHandler();
    if (handler instanceof Http11Protocol) {
        ((Http11Protocol) handler).setAddress(address);
    } else if (handler instanceof Http11NioProtocol) {
        ((Http11NioProtocol) handler).setAddress(address);
    } else {
        log.warn("Unknown handler type: {}", handler.getClass().getName());
    }

    // Start server
    try {
        // Add new Connector to set of Connectors for embedded server,
        // associated with Engine
        if (connectors == null || connectors.isEmpty()) {
            embedded.addConnector(connector);
            log.trace("Connector oName: {}", connector.getObjectName());
        } else {
            for (Connector ctr : connectors) {
                embedded.addConnector(ctr);
                log.trace("Connector oName: {}", ctr.getObjectName());
            }
        }

        log.info("Starting Tomcat servlet engine");
        embedded.start();

        LoaderBase.setApplicationLoader(new TomcatApplicationLoader(embedded, host, applicationContext));

        for (Container cont : host.findChildren()) {
            if (cont instanceof StandardContext) {
                StandardContext ctx = (StandardContext) cont;

                final ServletContext servletContext = ctx.getServletContext();
                log.debug("Context initialized: {}", servletContext.getContextPath());

                //set the hosts id
                servletContext.setAttribute("red5.host.id", getHostId());

                String prefix = servletContext.getRealPath("/");
                log.debug("Path: {}", prefix);

                try {
                    if (ctx.resourcesStart()) {
                        log.debug("Resources started");
                    }

                    log.debug("Context - available: {} privileged: {}, start time: {}, reloadable: {}",
                            new Object[] { ctx.getAvailable(), ctx.getPrivileged(), ctx.getStartTime(),
                                    ctx.getReloadable() });

                    Loader cldr = ctx.getLoader();
                    log.debug("Loader delegate: {} type: {}", cldr.getDelegate(), cldr.getClass().getName());
                    if (cldr instanceof WebappLoader) {
                        log.debug("WebappLoader class path: {}", ((WebappLoader) cldr).getClasspath());
                    }
                    final ClassLoader webClassLoader = cldr.getClassLoader();
                    log.debug("Webapp classloader: {}", webClassLoader);

                    // get the (spring) config file path
                    final String contextConfigLocation = servletContext.getInitParameter(
                            org.springframework.web.context.ContextLoader.CONFIG_LOCATION_PARAM) == null
                                    ? defaultSpringConfigLocation
                                    : servletContext.getInitParameter(
                                            org.springframework.web.context.ContextLoader.CONFIG_LOCATION_PARAM);
                    log.debug("Spring context config location: {}", contextConfigLocation);

                    // get the (spring) parent context key
                    final String parentContextKey = servletContext.getInitParameter(
                            org.springframework.web.context.ContextLoader.LOCATOR_FACTORY_KEY_PARAM) == null
                                    ? defaultParentContextKey
                                    : servletContext.getInitParameter(
                                            org.springframework.web.context.ContextLoader.LOCATOR_FACTORY_KEY_PARAM);
                    log.debug("Spring parent context key: {}", parentContextKey);

                    //set current threads classloader to the webapp classloader
                    Thread.currentThread().setContextClassLoader(webClassLoader);

                    //create a thread to speed-up application loading
                    Thread thread = new Thread("Launcher:" + servletContext.getContextPath()) {
                        public void run() {
                            //set thread context classloader to web classloader
                            Thread.currentThread().setContextClassLoader(webClassLoader);
                            //get the web app's parent context
                            ApplicationContext parentContext = null;
                            if (applicationContext.containsBean(parentContextKey)) {
                                parentContext = (ApplicationContext) applicationContext
                                        .getBean(parentContextKey);
                            } else {
                                log.warn("Parent context was not found: {}", parentContextKey);
                            }
                            // create a spring web application context
                            final String contextClass = servletContext.getInitParameter(
                                    org.springframework.web.context.ContextLoader.CONTEXT_CLASS_PARAM) == null
                                            ? XmlWebApplicationContext.class.getName()
                                            : servletContext.getInitParameter(
                                                    org.springframework.web.context.ContextLoader.CONTEXT_CLASS_PARAM);
                            //web app context (spring)
                            ConfigurableWebApplicationContext appctx = null;
                            try {
                                Class<?> clazz = Class.forName(contextClass, true, webClassLoader);
                                appctx = (ConfigurableWebApplicationContext) clazz.newInstance();
                            } catch (Throwable e) {
                                throw new RuntimeException("Failed to load webapplication context class.", e);
                            }
                            appctx.setConfigLocations(new String[] { contextConfigLocation });
                            appctx.setServletContext(servletContext);
                            //set parent context or use current app context
                            if (parentContext != null) {
                                appctx.setParent(parentContext);
                            } else {
                                appctx.setParent(applicationContext);
                            }
                            // set the root webapp ctx attr on the each servlet context so spring can find it later
                            servletContext.setAttribute(
                                    WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, appctx);
                            //refresh the factory
                            log.trace("Classloader prior to refresh: {}", appctx.getClassLoader());
                            appctx.refresh();
                            if (log.isDebugEnabled()) {
                                log.debug("Red5 app is active: {} running: {}", appctx.isActive(),
                                        appctx.isRunning());
                            }
                        }
                    };
                    thread.setDaemon(true);
                    thread.start();

                } catch (Throwable t) {
                    log.error("Error setting up context: {} due to: {}", servletContext.getContextPath(),
                            t.getMessage());
                    t.printStackTrace();
                } finally {
                    //reset the classloader
                    Thread.currentThread().setContextClassLoader(originalClassLoader);
                }
            }
        }

        // if everything is ok at this point then call the rtmpt and rtmps
        // beans so they will init
        if (applicationContext.containsBean("red5.core")) {
            ApplicationContext core = (ApplicationContext) applicationContext.getBean("red5.core");
            if (core.containsBean("rtmpt.server")) {
                log.debug("Initializing RTMPT");
                core.getBean("rtmpt.server");
                log.debug("Finished initializing RTMPT");
            } else {
                log.info("Dedicated RTMPT server configuration was not specified");
            }
            if (core.containsBean("rtmps.server")) {
                log.debug("Initializing RTMPS");
                core.getBean("rtmps.server");
                log.debug("Finished initializing RTMPS");
            } else {
                log.info("Dedicated RTMPS server configuration was not specified");
            }
        } else {
            log.info("Core context was not found");
        }
    } catch (Exception e) {
        if (e instanceof BindException || e.getMessage().indexOf("BindException") != -1) {
            log.error(
                    "Error loading tomcat, unable to bind connector. You may not have permission to use the selected port",
                    e);
        } else {
            log.error("Error loading tomcat", e);
        }
    } finally {
        registerJMX();
    }

}

From source file:org.brutusin.rpc.RpcWebInitializer.java

public void onStartup(final ServletContext ctx) throws ServletException {
    final RpcServlet rpcServlet = registerRpcServlet(ctx);
    final WebsocketFilter websocketFilter = new WebsocketFilter();
    FilterRegistration.Dynamic dynamic = ctx.addFilter(WebsocketFilter.class.getName(), websocketFilter);
    dynamic.addMappingForUrlPatterns(null, false, RpcConfig.getInstance().getPath() + "/wskt");
    JsonCodec.getInstance().registerStringFormat(MetaDataInputStream.class, "inputstream");
    final Bean<RpcSpringContext> rpcCtxBean = new Bean<RpcSpringContext>();
    ctx.addListener(new ServletRequestListener() {

        public void requestDestroyed(ServletRequestEvent sre) {
            GlobalThreadLocal.clear();/*from  w w  w . j a  va 2  s .  c o m*/
        }

        public void requestInitialized(ServletRequestEvent sre) {
            GlobalThreadLocal.set(new GlobalThreadLocal((HttpServletRequest) sre.getServletRequest(), null));
        }
    });
    ctx.addListener(new ServletContextListener() {

        public void contextInitialized(ServletContextEvent sce) {
            RpcSpringContext rpcCtx = createRpcSpringContext(ctx);
            rpcCtxBean.setValue(rpcCtx);
            rpcServlet.setRpcCtx(rpcCtx);
            initWebsocketRpcRuntime(ctx, rpcCtx);
            ctx.setAttribute(RpcSpringContext.class.getName(), rpcCtx);
        }

        public void contextDestroyed(ServletContextEvent sce) {
            LOGGER.info("Destroying RPC context");
            if (rpcCtxBean.getValue() != null) {
                rpcCtxBean.getValue().destroy();
            }
        }
    });
    ctx.addListener(new ServletContextAttributeListener() {
        public void attributeAdded(ServletContextAttributeEvent event) {
            if (event.getName().equals(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE)) {
                updateRootContext();
            }
        }

        public void attributeRemoved(ServletContextAttributeEvent event) {
            if (event.getName().equals(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE)) {
                updateRootContext();
            }
        }

        public void attributeReplaced(ServletContextAttributeEvent event) {
            if (event.getName().equals(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE)) {
                updateRootContext();
            }
        }

        private void updateRootContext() {
            WebApplicationContext rootCtx = WebApplicationContextUtils.getWebApplicationContext(ctx);
            if (rootCtx != null) {
                if (rpcCtxBean.getValue() != null) {
                    rpcCtxBean.getValue().setParent(rootCtx);
                }
                if (rootCtx.containsBean("springSecurityFilterChain")) {
                    LOGGER.info("Moving WebsocketFilter behind springSecurityFilterChain");
                    websocketFilter.disable();
                    FilterChainProxy fcp = (FilterChainProxy) rootCtx.getBean("springSecurityFilterChain");
                    fcp.getFilterChains().get(0).getFilters().add(new WebsocketFilter());
                }
            }
        }
    });
}

From source file:org.infoglue.cms.security.InfoGlueAuthenticationFilter.java

/**
 * This filter is basically what secures Infoglue and enforces the authentication framework.
 *///  w  w w.j a va 2  s  .c  o  m
public void doFilter(ServletRequest request, ServletResponse response, FilterChain fc)
        throws ServletException, IOException {
    HttpServletRequest httpServletRequest = (HttpServletRequest) request;
    HttpServletResponse httpServletResponse = (HttpServletResponse) response;

    try {
        if (CmsPropertyHandler.getServletContext() == null) {
            CmsPropertyHandler.setServletContext(httpServletRequest.getContextPath());
        }

        String URI = httpServletRequest.getRequestURI();
        String URL = httpServletRequest.getRequestURL().toString();
        if (logger.isInfoEnabled()) {
            logger.info("URI: + " + URI);
            logger.info("URL: + " + URL);
        }

        String requestURI = URLDecoder.decode(getContextRelativeURI(httpServletRequest), "UTF-8");
        if (URI == null)
            logger.error("URI was null - requestURI:" + requestURI);
        if (URL == null)
            logger.error("URL was null - requestURI:" + requestURI);
        if (requestURI == null)
            logger.error("requestURI was null");

        if (loginUrl == null) {
            logger.error("loginUrl was null - fix this.");
            loginUrl = "Login.action";
        }
        if (invalidLoginUrl == null) {
            logger.error("invalidLoginUrl was null - fix this.");
            invalidLoginUrl = "Login!invalidLogin.action";
        }
        if (logoutUrl == null) {
            logger.error("logoutUrl was null - fix this.");
            logoutUrl = "ExtranetLogin!logout.action";
        }

        if (uriMatcher == null) {
            logger.error("uriMatcher was null - fix this.");
            String filterURIs = filterConfig.getInitParameter(FILTER_URIS_PARAMETER);
            uriMatcher = URIMatcher.compilePatterns(splitString(filterURIs, ","), false);
        }

        if (!CmsPropertyHandler.getIsValidSetup()
                && (URI.indexOf("Install") == -1 && URI.indexOf(".action") > -1)) {
            httpServletResponse.sendRedirect("Install!input.action");
            return;
        }

        //Here are the url:s/paths that must be skipped by the security framework for it to work. Login screens etc must be reachable naturally.
        if (URI != null && URL != null
                && (URI.indexOf(loginUrl) > -1 || URL.indexOf(loginUrl) > -1 || URI.indexOf("Login.action") > -1
                        || URL.indexOf("Login.action") > -1 || URI.indexOf(invalidLoginUrl) > -1
                        || URL.indexOf(invalidLoginUrl) > -1 || URI.indexOf("Login!invalidLogin.action") > -1
                        || URL.indexOf("Login!invalidLogin.action") > -1 || URI.indexOf(logoutUrl) > -1
                        || URI.indexOf("Login!logout.action") > -1 || URL.indexOf(logoutUrl) > -1
                        || URI.indexOf("UpdateCache") > -1 || URI.indexOf("protectedRedirect.jsp") > -1
                        || uriMatcher.matches(requestURI))) {
            fc.doFilter(request, response);
            return;
        }

        // make sure we've got an HTTP request
        if (!(request instanceof HttpServletRequest) || !(response instanceof HttpServletResponse))
            throw new ServletException("InfoGlue Filter protects only HTTP resources");

        HttpSession session = ((HttpServletRequest) request).getSession();

        String sessionTimeout = CmsPropertyHandler.getSessionTimeout();
        try {
            Integer.parseInt(sessionTimeout);
        } catch (Exception e) {
            sessionTimeout = "1800";
        }
        if (sessionTimeout == null)
            sessionTimeout = "1800";

        session.setMaxInactiveInterval(new Integer(sessionTimeout).intValue());

        // if our attribute's already present, don't do anything
        //logger.info("User:" + session.getAttribute(INFOGLUE_FILTER_USER));
        if (session != null && session.getAttribute(INFOGLUE_FILTER_USER) != null) {
            //logger.info("Found user in session:" + session.getAttribute(INFOGLUE_FILTER_USER));
            //if(successLoginBaseUrl != null && !URL.startsWith(successLoginBaseUrl))
            //{
            //    checkSuccessRedirect(request, response, URL);
            //}
            //else
            //{
            fc.doFilter(request, response);
            return;
            //}
        }

        // otherwise, we need to authenticate somehow
        boolean isAdministrator = false;

        String userName = request.getParameter("j_username");
        String password = request.getParameter("j_password");

        if (userName != null && password != null) {
            String administratorUserName = CmsPropertyHandler.getAdministratorUserName();

            boolean matchesRootPassword = CmsPropertyHandler.getMatchesAdministratorPassword(password);
            isAdministrator = (userName.equalsIgnoreCase(administratorUserName) && matchesRootPassword) ? true
                    : false;
        }

        //First we check if the user is logged in to the container context
        if (!isAdministrator) {
            logger.info("Principal:" + httpServletRequest.getUserPrincipal());
            if (httpServletRequest.getUserPrincipal() != null
                    && !(httpServletRequest.getUserPrincipal() instanceof InfoGluePrincipal)) {
                userName = httpServletRequest.getUserPrincipal().getName();
                logger.info("Now trusting the container logged in identity...");
            }
        }

        String authenticatedUserName = userName;

        if (!isAdministrator) {
            String encodedUserNameCookie = httpHelper.getCookie(httpServletRequest, "iguserid");
            logger.info("encodedUserNameCookie:" + encodedUserNameCookie);
            if (encodedUserNameCookie != null && !encodedUserNameCookie.equals("")) {
                byte[] bytes = Base64.decodeBase64(encodedUserNameCookie);
                encodedUserNameCookie = new String(bytes, "utf-8");
                //encodedUserNameCookie = encodedUserNameCookie.replaceAll("IGEQ", "=");
                logger.info("encodedUserNameCookie:" + encodedUserNameCookie);
                String servletContextUserName = (String) filterConfig.getServletContext()
                        .getAttribute(encodedUserNameCookie);
                logger.info("servletContextUserName:" + servletContextUserName);
                if (servletContextUserName != null && !servletContextUserName.equals("")) {
                    authenticatedUserName = servletContextUserName;
                } else {
                    Cookie cookie_iguserid = new Cookie("iguserid", "none");
                    cookie_iguserid.setPath("/");
                    cookie_iguserid.setMaxAge(0);
                    httpServletResponse.addCookie(cookie_iguserid);

                    Cookie cookie_igpassword = new Cookie("igpassword", "none");
                    cookie_igpassword.setPath("/");
                    cookie_igpassword.setMaxAge(0);
                    httpServletResponse.addCookie(cookie_igpassword);

                    authenticatedUserName = authenticateUser(httpServletRequest, httpServletResponse, fc);
                }
            } else {
                authenticatedUserName = authenticateUser(httpServletRequest, httpServletResponse, fc);
            }
        }

        logger.info("authenticatedUserName:" + authenticatedUserName);

        if (authenticatedUserName != null) {
            logger.info("Getting the principal from user name:" + authenticatedUserName);

            InfoGluePrincipal user = getAuthenticatedUser(authenticatedUserName);
            if (user == null || (!user.getIsAdministrator() && !hasAuthorizedRole(user))) {
                //throw new Exception("This user is not authorized to log in...");
                httpServletResponse.sendRedirect("unauthorizedLogin.jsp");

                NotificationMessage notificationMessage = new NotificationMessage("Authorization failed:",
                        "Authorization", authenticatedUserName, NotificationMessage.AUTHORIZATION_FAILED,
                        "" + authenticatedUserName, "name");
                TransactionHistoryController.getController().create(notificationMessage);

                return;
            }

            //TODO - we must fix so these caches are individual to the person - now a login will slow down for all
            //CacheController.clearCache("authorizationCache");
            //CacheController.clearCache("personalAuthorizationCache", user.getName());
            CacheController.clearCacheForGroup("personalAuthorizationCache", user.getName());

            // Store the authenticated user in the session
            if (session != null) {
                session.setAttribute(INFOGLUE_FILTER_USER, user);
                setUserProperties(session, user);
            }

            //TEST - transferring auth to deliverworking
            try {
                if (userName != null && password != null) {
                    DesEncryptionHelper encHelper = new DesEncryptionHelper();
                    String encryptedName = encHelper.encrypt(userName);
                    String encryptedPassword = encHelper.encrypt(password);

                    String encryptedNameAsBase64 = Base64
                            .encodeBase64URLSafeString(encryptedName.getBytes("utf-8"));
                    String encryptedPasswordAsBase64 = Base64
                            .encodeBase64URLSafeString(encryptedPassword.getBytes("utf-8"));

                    String deliverBaseUrl = CmsPropertyHandler.getComponentRendererUrl();
                    String[] parts = deliverBaseUrl.split("/");

                    deliverBaseUrl = "/" + parts[parts.length - 1];
                    //logger.info("used cmsBaseUrl:" + cmsBaseUrl);

                    ServletContext servletContext = filterConfig.getServletContext().getContext(deliverBaseUrl);
                    if (servletContext == null) {
                        logger.error("Could not autologin to " + deliverBaseUrl
                                + ". Set cross context = true in Tomcat config.");
                    } else {
                        logger.info("Added encryptedName:" + encryptedName + " = " + user.getName()
                                + " to deliver context");
                        servletContext.setAttribute(encryptedName, user.getName());
                    }

                    int cmsCookieTimeout = 1800; //30 minutes default
                    String cmsCookieTimeoutString = null; //CmsPropertyHandler.getCmsCookieTimeout();
                    if (cmsCookieTimeoutString != null) {
                        try {
                            cmsCookieTimeout = Integer.parseInt(cmsCookieTimeoutString.trim());
                        } catch (Exception e) {
                        }
                    }

                    //Cookie cookie_iguserid = new Cookie("iguserid", encryptedName.replaceAll("=", "IGEQ"));
                    Cookie cookie_iguserid = new Cookie("iguserid", encryptedNameAsBase64);
                    cookie_iguserid.setPath("/");
                    cookie_iguserid.setMaxAge(cmsCookieTimeout);
                    httpServletResponse.addCookie(cookie_iguserid);

                    //Cookie cookie_igpassword = new Cookie ("igpassword", encryptedPassword.replaceAll("=", "IGEQ"));
                    Cookie cookie_igpassword = new Cookie("igpassword", encryptedPasswordAsBase64);
                    cookie_igpassword.setPath("/");
                    cookie_igpassword.setMaxAge(cmsCookieTimeout);
                    httpServletResponse.addCookie(cookie_igpassword);

                    //logger.info(encryptedName + "=" + userName);
                    //logger.info("After attribute:" + servletContext.getAttribute(encryptedName));
                }
            } catch (Exception e) {
                logger.error("Error: " + e.getMessage(), e);
            }
            //END TEST

            String logUserName = userName;
            if (logUserName == null || logUserName.equals("") && user != null)
                logUserName = user.getName();
            if (logUserName == null || logUserName.equals(""))
                logUserName = authenticatedUserName;
            if (logUserName == null || logUserName.equals(""))
                logUserName = "Unknown";

            NotificationMessage notificationMessage = new NotificationMessage("Login success:",
                    "Authentication", logUserName, NotificationMessage.AUTHENTICATION_SUCCESS,
                    "" + authenticatedUserName, "name");
            TransactionHistoryController.getController().create(notificationMessage);

            if (successLoginBaseUrl != null && !URL.startsWith(successLoginBaseUrl)) {
                checkSuccessRedirect(request, response, URL);
            } else {
                fc.doFilter(request, response);
                return;
            }
        } else {
            if (userName != null && !userName.equals("")) {
                NotificationMessage notificationMessage = new NotificationMessage("Login failed:",
                        "Authentication", userName, NotificationMessage.AUTHENTICATION_FAILED, "" + userName,
                        "name");
                TransactionHistoryController.getController().create(notificationMessage);
            }
        }
    } catch (Exception e) {
        logger.error("Error authenticating user:" + e.getMessage(), e);
        httpServletRequest.setAttribute("error", new Exception(
                "Error in authentication filter - look at the server error log (usually catalina.out) for reason but the most common one is problem connecting to the database or a faulty connection user or limited access for that account."));
        httpServletResponse.sendError(500);
        return;
    }
}

From source file:org.musicrecital.webapp.listener.StartupListener.java

/**
 * {@inheritDoc}/*w ww . ja va 2 s  .c  o  m*/
 */
@SuppressWarnings("unchecked")
public void contextInitialized(ServletContextEvent event) {
    log.debug("Initializing context...");

    ServletContext context = event.getServletContext();

    // Orion starts Servlets before Listeners, so check if the config
    // object already exists
    Map<String, Object> config = (HashMap<String, Object>) context.getAttribute(Constants.CONFIG);

    if (config == null) {
        config = new HashMap<String, Object>();
    }

    ApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(context);

    PasswordEncoder passwordEncoder = null;
    try {
        ProviderManager provider = (ProviderManager) ctx
                .getBean("org.springframework.security.authentication.ProviderManager#0");
        for (Object o : provider.getProviders()) {
            AuthenticationProvider p = (AuthenticationProvider) o;
            if (p instanceof RememberMeAuthenticationProvider) {
                config.put("rememberMeEnabled", Boolean.TRUE);
            } else if (ctx.getBean("passwordEncoder") != null) {
                passwordEncoder = (PasswordEncoder) ctx.getBean("passwordEncoder");
            }
        }
    } catch (NoSuchBeanDefinitionException n) {
        log.debug("authenticationManager bean not found, assuming test and ignoring...");
        // ignore, should only happen when testing
    }

    context.setAttribute(Constants.CONFIG, config);

    // output the retrieved values for the Init and Context Parameters
    if (log.isDebugEnabled()) {
        log.debug("Remember Me Enabled? " + config.get("rememberMeEnabled"));
        if (passwordEncoder != null) {
            log.debug("Password Encoder: " + passwordEncoder.getClass().getSimpleName());
        }
        log.debug("Populating drop-downs...");
    }

    setupContext(context);

    // Determine version number for CSS and JS Assets
    String appVersion = null;
    try {
        InputStream is = context.getResourceAsStream("/META-INF/MANIFEST.MF");
        if (is == null) {
            log.warn("META-INF/MANIFEST.MF not found.");
        } else {
            Manifest mf = new Manifest();
            mf.read(is);
            Attributes atts = mf.getMainAttributes();
            appVersion = atts.getValue("Implementation-Version");
        }
    } catch (IOException e) {
        log.error("I/O Exception reading manifest: " + e.getMessage());
    }

    // If there was a build number defined in the war, then use it for
    // the cache buster. Otherwise, assume we are in development mode
    // and use a random cache buster so developers don't have to clear
    // their browser cache.
    if (appVersion == null || appVersion.contains("SNAPSHOT")) {
        appVersion = "" + new Random().nextInt(100000);
    }

    log.info("Application version set to: " + appVersion);
    context.setAttribute(Constants.ASSETS_VERSION, appVersion);
}