Example usage for javax.servlet ServletContext getServletContextName

List of usage examples for javax.servlet ServletContext getServletContextName

Introduction

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

Prototype

public String getServletContextName();

Source Link

Document

Returns the name of this web application corresponding to this ServletContext as specified in the deployment descriptor for this web application by the display-name element.

Usage

From source file:de.kaiserpfalzEdv.commons.jee.servlet.util.ServletContextParamReader.java

/**
 * @param context The application servlet context.
 * @throws IllegalArgumentException If the servlet context is NULL.
 *///from   w  ww  .  ja  v  a  2  s.  co m
public ServletContextParamReader(ServletContext context) {
    checkArgument(context != null, "Can't read configuration from NULL context.");

    this.context = context;

    //noinspection ConstantConditions
    LOG.info("Loading configuration from context: {}", context.getServletContextName());
}

From source file:org.smigo.config.WebAppInitializer.java

@Override
protected void beforeSpringSecurityFilterChain(ServletContext servletContext) {
    super.beforeSpringSecurityFilterChain(servletContext);
    log.info("Starting servlet context");
    log.info("contextName: " + servletContext.getServletContextName());
    log.info("contextPath:" + servletContext.getContextPath());
    log.info("effectiveMajorVersion:" + servletContext.getEffectiveMajorVersion());
    log.info("effectiveMinorVersion:" + servletContext.getEffectiveMinorVersion());
    log.info("majorVersion:" + servletContext.getMajorVersion());
    log.info("minorVersion:" + servletContext.getMinorVersion());
    log.info("serverInfo:" + servletContext.getServerInfo());
    //               ", virtualServerName:" + servletContext.getVirtualServerName() +
    log.info("toString:" + servletContext.toString());

    for (Enumeration<String> e = servletContext.getAttributeNames(); e.hasMoreElements();) {
        log.info("Attribute:" + e.nextElement());
    }/*w  w  w  .j a va2  s .  c om*/
    for (Map.Entry<String, String> env : System.getenv().entrySet()) {
        log.info("System env:" + env.toString());
    }
    for (Map.Entry<Object, Object> prop : System.getProperties().entrySet()) {
        log.info("System prop:" + prop.toString());
    }

    final String profile = System.getProperty("smigoProfile", EnvironmentProfile.PRODUCTION);
    log.info("Starting with profile " + profile);

    WebApplicationContext context = new AnnotationConfigWebApplicationContext() {
        {
            register(WebConfiguration.class);
            setDisplayName("SomeRandomName");
            getEnvironment().setActiveProfiles(profile);
        }
    };

    FilterRegistration.Dynamic characterEncodingFilter = servletContext.addFilter("CharacterEncodingFilter",
            new CharacterEncodingFilter());
    characterEncodingFilter.setInitParameter("encoding", "UTF-8");
    characterEncodingFilter.setInitParameter("forceEncoding", "true");
    characterEncodingFilter.addMappingForUrlPatterns(null, false, "/*");

    servletContext.addListener(new RequestContextListener());
    servletContext.addListener(new ContextLoaderListener(context));

    //http://stackoverflow.com/questions/4811877/share-session-data-between-2-subdomains
    //        servletContext.getSessionCookieConfig().setDomain(getDomain());

    DispatcherServlet dispatcherServlet = new DispatcherServlet(context);
    dispatcherServlet.setThrowExceptionIfNoHandlerFound(false);
    servletContext.addServlet("dispatcher", dispatcherServlet).addMapping("/");
}

From source file:org.atomserver.testutils.client.JettyWebAppTestCase.java

/**
 * return the Application Spring WebApplicationContext.
 * Its a bit convoluted to get at it from here, but ultimately its doable.
 * We have to traverse from the Jetty Server, until we get to the ServletContext.
 * NOTE: this code is entirely dependent on the structure of jettyBeans.xml
 * Thus, if that Bean changes, so must this code !!!
 */// w w  w  . ja v a 2  s  .  c o m
protected ApplicationContext getSpringFactory() throws Exception {
    if (appSpringFactory == null) {
        Server jserver = getJettyServer();

        WebAppContext webappContext = (WebAppContext) jserver.getHandler();
        log.debug("webappContext= " + webappContext);

        servletHandler = webappContext.getServletHandler();
        log.debug("ServletHandler = " + servletHandler);

        ServletContext servletContext = servletHandler.getServletContext();
        log.debug("servletContext= " + servletContext);

        servletContextName = servletContext.getServletContextName();
        if (servletContextName == null) {
            throw new RuntimeException("No servletContextName defined for atomserver");
        }
        // will come back as e.g. /atomserver/
        servletContextName = StringUtils.strip(servletContextName, "/");
        log.debug("****************** servletContextName= " + servletContextName);

        appSpringFactory = WebApplicationContextUtils.getWebApplicationContext(servletContext);
    }
    return appSpringFactory;
}

From source file:com.liferay.portal.deploy.hot.ExtHotDeployListener.java

protected void doInvokeUndeploy(HotDeployEvent event) throws Exception {
    ServletContext servletContext = event.getServletContext();

    String servletContextName = servletContext.getServletContextName();

    if (_log.isDebugEnabled()) {
        _log.debug("Invoking undeploy for " + servletContextName);
    }/*from  w  ww .j  a va 2s .c om*/

    String xml = HttpUtil
            .URLtoString(servletContext.getResource("/WEB-INF/ext-" + servletContextName + ".xml"));

    if (xml == null) {
        return;
    }

    if (_log.isInfoEnabled()) {
        _log.info("Extension environment for " + servletContextName + " will not be undeployed");
    }
}

From source file:com.liferay.portal.deploy.hot.ExtHotDeployListener.java

protected void copyJar(ServletContext servletContext, String dir, String jarName) throws Exception {

    String servletContextName = servletContext.getServletContextName();

    String jarFullName = "/WEB-INF/" + jarName + "/" + jarName + ".jar";

    InputStream is = servletContext.getResourceAsStream(jarFullName);

    if (is == null) {
        throw new HotDeployException(jarFullName + " does not exist");
    }/*from w w  w. j  a v a  2  s  . c o m*/

    String newJarFullName = dir + "ext-" + servletContextName + jarName.substring(3) + ".jar";

    StreamUtil.transfer(is, new FileOutputStream(new File(newJarFullName)));
}

From source file:com.liferay.portal.deploy.hot.ExtHotDeployListener.java

protected void installExt(ServletContext servletContext, ClassLoader portletClassLoader) throws Exception {

    String servletContextName = servletContext.getServletContextName();

    String globalLibDir = PortalUtil.getGlobalLibDir();
    String portalWebDir = PortalUtil.getPortalWebDir();
    String portalLibDir = PortalUtil.getPortalLibDir();
    String pluginWebDir = WebDirDetector.getRootDir(portletClassLoader);

    for (String jarName : ExtRegistry.EXT_PLUGIN_JARS_GLOBAL_CL) {
        copyJar(servletContext, globalLibDir, jarName);
    }/*from   w w w .j  a  v a2  s  .c  o  m*/
    for (String jarName : ExtRegistry.EXT_PLUGIN_JARS_PORTAL_CL) {
        copyJar(servletContext, portalLibDir, jarName);
    }

    mergeWebXml(portalWebDir, pluginWebDir);

    mergePortalProperties(portalWebDir, servletContext);

    copyWebDirectory(pluginWebDir + "WEB-INF/ext-web/docroot/", portalWebDir);

    mergeServiceJS(portalWebDir, servletContext);

    createWebInfJar(portalWebDir, pluginWebDir, servletContextName);

    FileUtil.copyFile(pluginWebDir + "WEB-INF/ext-" + servletContextName + ".xml",
            portalWebDir + "WEB-INF/ext-" + servletContextName + ".xml");

    ExtRegistry.registerExt(servletContext);
}

From source file:de.betterform.agent.web.servlet.XFormsRepeater.java

private void processForm(HttpServletRequest request, HttpServletResponse response, HttpSession session)
        throws ServletException {
    String url = request.getRequestURL().toString();
    ServletContext context = this.getServletContext();

    if (request.getAttribute("XFormsInputStream") != null) {
        System.out.println("Request has an extra Stream!: ");
        System.out.println("Context: " + context.getServletContextName());
        System.out.println("Original Request URL: " + request.getAttribute("betterform.base.url"));
        url = (String) request.getAttribute(WebProcessor.FORWARD_URL);
    }//from   w  ww .j  a v  a  2s.  c o m
    //        XFormsSession xFormsSession = null;
    WebProcessor webProcessor = null;
    try {
        webProcessor = new FluxProcessor();
        webProcessor.setRequest(request);
        webProcessor.setResponse(response);
        webProcessor.setHttpSession(session);
        webProcessor.setBaseURI(url);
        webProcessor.setContext(context);
        webProcessor.configure();
        webProcessor.setXForms();
        webProcessor.init();
        webProcessor.handleRequest();
    } catch (Exception e) {
        if (webProcessor != null) {
            // attempt to shutdown processor
            try {
                webProcessor.shutdown();
            } catch (XFormsException xfe) {
                //                    LOG.error("Could not shutdown Processor: Error: " + xfe.getMessage() + " Cause: " + xfe.getCause());

            }
            // store exception
            session.setAttribute("betterform.exception", e);
            request.setAttribute("betterform.exception", e);
            request.setAttribute("betterform.referer", request.getRequestURL().toString());
            session.setAttribute("betterform.referer", request.getRequestURL().toString());

            //remove session from XFormsSessionManager
            WebUtil.removeSession(webProcessor.getKey());
            throw new ServletException(e);
        }
    }
}

From source file:com.liferay.portal.servlet.PortletContextListener.java

public void contextInitialized(ServletContextEvent sce) {
    try {/* ww  w.j av  a 2s. c  o  m*/

        // Servlet context

        ServletContext ctx = sce.getServletContext();

        _servletContextName = StringUtil.replace(ctx.getServletContextName(), StringPool.SPACE,
                StringPool.UNDERLINE);

        // Company ids

        _companyIds = StringUtil.split(ctx.getInitParameter("company_id"));

        // Class loader

        ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();

        // Initialize portlets

        String[] xmls = new String[] { Http.URLtoString(ctx.getResource("/WEB-INF/portlet.xml")),
                Http.URLtoString(ctx.getResource("/WEB-INF/liferay-portlet.xml")) };

        _portlets = PortletManagerUtil.initWAR(_servletContextName, xmls);

        // Portlet context wrapper

        Iterator itr1 = _portlets.iterator();

        while (itr1.hasNext()) {
            Portlet portlet = (Portlet) itr1.next();

            javax.portlet.Portlet portletInstance = (javax.portlet.Portlet) contextClassLoader
                    .loadClass(portlet.getPortletClass()).newInstance();

            Indexer indexerInstance = null;
            if (Validator.isNotNull(portlet.getIndexerClass())) {
                indexerInstance = (Indexer) contextClassLoader.loadClass(portlet.getIndexerClass())
                        .newInstance();
            }

            Scheduler schedulerInstance = null;
            if (Validator.isNotNull(portlet.getSchedulerClass())) {
                schedulerInstance = (Scheduler) contextClassLoader.loadClass(portlet.getSchedulerClass())
                        .newInstance();
            }

            PreferencesValidator prefsValidator = null;
            if (Validator.isNotNull(portlet.getPreferencesValidator())) {
                prefsValidator = (PreferencesValidator) contextClassLoader
                        .loadClass(portlet.getPreferencesValidator()).newInstance();

                try {
                    if (GetterUtil.getBoolean(PropsUtil.get(PropsUtil.PREFERENCE_VALIDATE_ON_STARTUP))) {

                        prefsValidator.validate(
                                PortletPreferencesSerializer.fromDefaultXML(portlet.getDefaultPreferences()));
                    }
                } catch (Exception e1) {
                    _log.warn("Portlet with the name " + portlet.getPortletId()
                            + " does not have valid default preferences");
                }
            }

            Map resourceBundles = null;

            if (Validator.isNotNull(portlet.getResourceBundle())) {
                resourceBundles = CollectionFactory.getHashMap();

                Iterator itr2 = portlet.getSupportedLocales().iterator();

                while (itr2.hasNext()) {
                    String supportedLocale = (String) itr2.next();

                    Locale locale = new Locale(supportedLocale);

                    try {
                        ResourceBundle resourceBundle = ResourceBundle.getBundle(portlet.getResourceBundle(),
                                locale, contextClassLoader);

                        resourceBundles.put(locale.getLanguage(), resourceBundle);
                    } catch (MissingResourceException mre) {
                        _log.warn(mre.getMessage());
                    }
                }
            }

            Map customUserAttributes = CollectionFactory.getHashMap();

            Iterator itr2 = portlet.getCustomUserAttributes().entrySet().iterator();

            while (itr2.hasNext()) {
                Map.Entry entry = (Map.Entry) itr2.next();

                String attrName = (String) entry.getKey();
                String attrCustomClass = (String) entry.getValue();

                customUserAttributes.put(attrCustomClass,
                        contextClassLoader.loadClass(attrCustomClass).newInstance());
            }

            PortletContextWrapper pcw = new PortletContextWrapper(portlet.getPortletId(), ctx, portletInstance,
                    indexerInstance, schedulerInstance, prefsValidator, resourceBundles, customUserAttributes);

            PortletContextPool.put(portlet.getPortletId(), pcw);
        }

        // Portlet class loader

        String servletPath = ctx.getRealPath("/");
        if (!servletPath.endsWith("/") && !servletPath.endsWith("\\")) {
            servletPath += "/";
        }

        File servletClasses = new File(servletPath + "WEB-INF/classes");
        File servletLib = new File(servletPath + "WEB-INF/lib");

        List urls = new ArrayList();

        if (servletClasses.exists()) {
            urls.add(new URL("file:" + servletClasses + "/"));
        }

        if (servletLib.exists()) {
            String[] jars = FileUtil.listFiles(servletLib);

            for (int i = 0; i < jars.length; i++) {
                urls.add(new URL("file:" + servletLib + "/" + jars[i]));
            }
        }

        URLClassLoader portletClassLoader = new URLClassLoader((URL[]) urls.toArray(new URL[0]),
                contextClassLoader);

        ctx.setAttribute(WebKeys.PORTLET_CLASS_LOADER, portletClassLoader);

        // Portlet display

        String xml = Http.URLtoString(ctx.getResource("/WEB-INF/liferay-display.xml"));

        Map newCategories = PortletManagerUtil.getWARDisplay(_servletContextName, xml);

        for (int i = 0; i < _companyIds.length; i++) {
            String companyId = _companyIds[i];

            Map oldCategories = (Map) WebAppPool.get(companyId, WebKeys.PORTLET_DISPLAY);

            Map mergedCategories = PortalUtil.mergeCategories(oldCategories, newCategories);

            WebAppPool.put(companyId, WebKeys.PORTLET_DISPLAY, mergedCategories);
        }

        // Reinitialize portal properties

        PropsUtil.init();
    } catch (Exception e2) {
        Logger.error(this, e2.getMessage(), e2);
    }
}

From source file:com.liferay.portal.deploy.hot.ExtHotDeployListener.java

protected void doInvokeDeploy(HotDeployEvent event) throws Exception {
    ServletContext servletContext = event.getServletContext();

    String servletContextName = servletContext.getServletContextName();

    if (_log.isDebugEnabled()) {
        _log.debug("Invoking deploy for " + servletContextName);
    }//from w  w  w  .  j a v  a2 s.  c  om

    String xml = HttpUtil
            .URLtoString(servletContext.getResource("/WEB-INF/ext-" + servletContextName + ".xml"));

    if (xml == null) {
        return;
    }

    if (_log.isInfoEnabled()) {
        _log.info("Registering extension environment for " + servletContextName);
    }

    if (ExtRegistry.isRegistered(servletContextName)) {
        if (_log.isInfoEnabled()) {
            _log.info("Extension environment for " + servletContextName + " has been applied.");
        }

        return;
    }

    Map<String, Set<String>> conflicts = ExtRegistry.getConflicts(servletContext);

    if (!conflicts.isEmpty()) {
        StringBundler sb = new StringBundler();

        sb.append("Extension environment for " + servletContextName
                + " cannot be applied because of detected conflicts:");

        Iterator<Map.Entry<String, Set<String>>> itr = conflicts.entrySet().iterator();

        while (itr.hasNext()) {
            Map.Entry<String, Set<String>> entry = itr.next();

            String conflictServletContextName = entry.getKey();
            Set<String> conflictFiles = entry.getValue();

            sb.append("\n\t");
            sb.append(conflictServletContextName);
            sb.append(":");

            for (String conflictFile : conflictFiles) {
                sb.append("\n\t\t");
                sb.append(conflictFile);
            }
        }

        _log.error(sb.toString());

        return;
    }

    installExt(servletContext, event.getContextClassLoader());

    FileAvailabilityUtil.reset();

    if (_log.isInfoEnabled()) {
        _log.info("Extension environment for " + servletContextName
                + " has been applied. You must reboot the server and " + "redeploy all other plugins.");
    }
}

From source file:ContextLogger.java

public void contextInitialized(ServletContextEvent sce) {

    ServletContext context = sce.getServletContext();

    String realPath = context.getRealPath("/");
    String fileSep = System.getProperty("file.separator");

    if (realPath != null && (!realPath.endsWith(fileSep)))
        realPath = realPath + fileSep;//from  w  w w  .ja  v  a  2s. c om
    //Initialize logger here:
    PropertyConfigurator.configure(realPath + "WEB-INF/classes/" + context.getInitParameter("logger-config"));
    log = Logger.getLogger(ContextLogger.class);

    String name = context.getServletContextName();
    //log request about servlet context being initialized
    log.info("ServletContext ready: " + (name == null ? "" : name));

}