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:org.sakaiproject.component.impl.SakaiContextLoader.java

/**
  * Allows loading/override of custom bean definitions from sakai.home
  *//w w w.j av  a  2  s  . c  o m
  * <p>The pattern is the 'servlet_name-context.xml'</p>
  *
  * @param servletContext current servlet context
  * @return the new WebApplicationContext
  * @throws org.springframework.beans.BeansException
  *          if the context couldn't be initialized
  */
@Override
public WebApplicationContext initWebApplicationContext(ServletContext servletContext) throws BeansException {

    ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext) super.initWebApplicationContext(
            servletContext);
    // optionally look in sakai home for additional bean deifinitions to load
    if (cwac != null) {
        final String servletName = servletContext.getServletContextName();
        String location = getHomeBeanDefinitionIfExists(servletName);
        if (StringUtils.isNotBlank(location)) {
            log.debug("Servlet " + servletName + " is attempting to load bean definition [" + location + "]");
            XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(
                    (BeanDefinitionRegistry) cwac.getBeanFactory());
            try {
                int loaded = reader.loadBeanDefinitions(new FileSystemResource(location));
                log.info("Servlet " + servletName + " loaded " + loaded + " beans from [" + location + "]");
                AnnotationConfigUtils.registerAnnotationConfigProcessors(reader.getRegistry());
                cwac.getBeanFactory().preInstantiateSingletons();
            } catch (BeanDefinitionStoreException bdse) {
                log.warn("Failure loading beans from [" + location + "]", bdse);
            } catch (BeanCreationException bce) {
                log.warn("Failure instantiating beans from [" + location + "]", bce);
            }
        }
    }
    return cwac;
}

From source file:org.sakaiproject.portal.render.portlet.PortletToolRenderService.java

private boolean isPortletApplication(ServletContext context, ToolConfiguration configuration)
        throws ToolRenderException, MalformedURLException {
    SakaiPortletWindow window = registry.getOrCreatePortletWindow(configuration);
    if (window == null) {
        return false;
    }/*from   w w  w .  ja  v  a  2 s . c o m*/
    if (LOG.isDebugEnabled()) {
        LOG.debug("Checking context for potential portlet ");
    }
    ServletContext crossContext = context.getContext(window.getContextPath());
    if (LOG.isDebugEnabled()) {
        LOG.debug("Got servlet context as  " + crossContext);
        LOG.debug("Getting Context for path " + window.getContextPath());
        LOG.debug("Base Path " + crossContext.getRealPath("/"));
        LOG.debug("Context Name " + crossContext.getServletContextName());
        LOG.debug("Server Info " + crossContext.getServerInfo());
        LOG.debug("      and it is a portlet ? :" + (crossContext.getResource("/WEB-INF/portlet.xml") != null));
    }
    return crossContext.getResource("/WEB-INF/portlet.xml") != null;
}

From source file:org.sakaiproject.site.tool.SiteAction.java

private String setMoreInfoPath(ServletContext ctx) {
    String rpath = ctx.getRealPath("");
    String ctxPath = ctx.getServletContextName();
    String rserve = StringUtils.remove(rpath, ctxPath);
    return rserve;
}

From source file:org.sindice.analytics.servlet.ServletConfigurationContextListener.java

@Override
public void contextInitialized(ServletContextEvent sce) {
    final ServletContext context = sce.getServletContext();
    String contextPath = context.getContextPath().replaceFirst("^/", "");
    if (contextPath.equals("")) {
        // application deployed in ROOT context
        String applicationName = context.getInitParameter("applicationName");
        if (applicationName != null && !applicationName.equals("")) {
            contextPath = "ROOT_" + applicationName;
        } else {//from  w  ww .  ja v a  2  s.  co  m
            contextPath = "ROOT";
        }
        logger.warn("Application deployed in ROOT context.");
    } else {
        logger.info("Application deployed in [" + contextPath + "] context.");
    }
    logger.info("Will use [" + contextPath + "] as a part of a path for reading/storing configuration");

    String servletContextName = context.getServletContextName();
    addEnvToContext(context);

    String sindiceHome = null;
    // FOR DEBIAN PACKAGE LOD2 PROJECT INTEGRATION
    // check that following directory exists
    // if yes please use it
    if (new File("/etc/" + contextPath + "/config.xml").exists()) {
        sindiceHome = "/etc";
        logger.info("Found config.xml at [/etc/" + contextPath + "/config.xml]. Setting sindiceHome to : ["
                + sindiceHome + "]");
    } else {
        logger.info(
                "File /etc/" + contextPath + "/config.xml does not exists will try to determine sindiceHome");
    }
    // END DEBIAN PACKAGE LOD2 PROJECT INTEGRATION
    if (sindiceHome == null && context.getAttribute("sindice.home") != null) {
        sindiceHome = (String) context.getAttribute("sindice.home");
        logger.info("Setting sindiceHome from sindice.home env variable to [" + sindiceHome + "]");
    }
    if (sindiceHome == null && context.getAttribute("SINDICE_HOME") != null) {
        sindiceHome = (String) context.getAttribute("SINDICE_HOME");
        logger.info("Setting sindiceHome from SINDICE_HOME env variable to [" + sindiceHome + "]");
    }
    if (sindiceHome == null || "".equals(sindiceHome.trim())) {
        String userHome = (String) context.getAttribute("user.home");
        sindiceHome = (userHome == null ? "" : userHome) + File.separatorChar + "sindice";
        logger.warn("Neither sindice.home nor SINDICE_HOME are not defined, assuming {}", sindiceHome);
    }

    logger.info("Looking for configuration in [" + sindiceHome + File.separatorChar + contextPath + "]");

    // important to set these two as they are used later in logback.xml
    context.setAttribute("sindice.home", sindiceHome);
    context.setAttribute("app.name", contextPath);

    configFolder = new File(sindiceHome + File.separatorChar + contextPath);
    if (!(configFolder.exists() && configFolder.isDirectory())) {
        logger.warn("Missing configuration folder {}", configFolder);
        if (configFolder.mkdirs()) {
            logger.warn("Creating default configuration at " + configFolder);

        } else {
            // set logging level to INFO
            configureLogging(context, configFolder);
            return;
        }
    }
    // does a specific folder exist for this servlet context?
    if (servletContextName == null) {
        logger.error("specify display-name element in web.xml !!! ");
    } else {
        File specificFolder = new File(configFolder, servletContextName);
        if (specificFolder.exists() && specificFolder.isDirectory()) {
            configFolder = specificFolder;
        }
    }
    logger.info("loading configuration from folder {}", configFolder);
    configureLogging(context, configFolder);
    final XMLConfiguration config = createXMLConfiguration(context);
    File applicationConfigFile = new File(configFolder, "config.xml");
    if (!applicationConfigFile.exists()) {
        logger.warn("missing application config file {}", applicationConfigFile);
        loadDefaultConfiguration(config, applicationConfigFile);
    } else {
        try {
            config.load(applicationConfigFile);
            logger.info("parsed {}", applicationConfigFile);
        } catch (ConfigurationException e) {
            logger.error("Could not load configuration from {}", applicationConfigFile, e);
            loadDefaultConfiguration(config, null);
        }
    }
    context.setAttribute("config", config);
    logger.info("config now availabe via the following line of code\n"
            + "    XMLConfiguration appConfig = (XMLConfiguration) servletContext.getAttribute(\"config\");");

    logger.info("Starting up {}", servletContextName);
}

From source file:org.sindice.servlet.sparqlqueryservlet.ServletConfigurationContextListener.java

@Override
public void contextInitialized(ServletContextEvent sce) {
    final ServletContext context = sce.getServletContext();
    String contextPath = context.getContextPath().replaceFirst("^/", "");
    if (contextPath.equals("")) {
        // application deployed in ROOT context
        String applicationName = context.getInitParameter("applicationName");
        if (applicationName != null && !applicationName.equals("")) {
            contextPath = "ROOT_" + applicationName;
        } else {//from  w ww .  ja  v a  2  s. co m
            contextPath = "ROOT";
        }
        logger.warn("Application deployed in ROOT context.");
    } else {
        logger.info("Application deployed in [" + contextPath + "] context.");
    }
    logger.info("Will use [" + contextPath + "] as a part of a path for reading/storing configuration");

    String servletContextName = context.getServletContextName();
    addEnvToContext(context);

    String sindiceHome = null;
    // FOR DEBIAN PACKAGE LOD2 PROJECT INTEGRATION
    // check that following directory exists
    // if yes please use it
    if (new File("/etc/" + contextPath + "/config.xml").exists()) {
        sindiceHome = "/etc";
        logger.info("Found config.xml at [/etc/" + contextPath + "/config.xml]. Setting sindiceHome to : ["
                + sindiceHome + "]");
    } else {
        logger.info(
                "File /etc/" + contextPath + "/config.xml does not exists will try to determine sindiceHome");
    }
    // END DEBIAN PACKAGE LOD2 PROJECT INTEGRATION
    if (sindiceHome == null && context.getAttribute("sindice.home") != null) {
        sindiceHome = (String) context.getAttribute("sindice.home");
        logger.info("Setting sindiceHome from sindice.home env variable to [" + sindiceHome + "]");
    }
    if (sindiceHome == null && context.getAttribute("SINDICE_HOME") != null) {
        sindiceHome = (String) context.getAttribute("SINDICE_HOME");
        logger.info("Setting sindiceHome from SINDICE_HOME env variable to [" + sindiceHome + "]");
    }
    if (sindiceHome == null || "".equals(sindiceHome.trim())) {
        String userHome = (String) context.getAttribute("user.home");
        sindiceHome = (userHome == null ? "" : userHome) + File.separatorChar + "sindice";
        logger.warn("Neither sindice.home nor SINDICE_HOME are not defined, assuming {}", sindiceHome);
    }

    logger.info("Looking for configuration in [" + sindiceHome + File.separatorChar + contextPath + "]");

    // important to set these two as they are used later in logback.xml
    context.setAttribute("sindice.home", sindiceHome);
    context.setAttribute("app.name", contextPath);

    File configFolder = new File(sindiceHome + File.separatorChar + contextPath);
    if (!(configFolder.exists() && configFolder.isDirectory())) {
        logger.warn("Missing configuration folder {}", configFolder);
        if (configFolder.mkdirs()) {
            logger.warn("Creating default configuration at " + configFolder);

        } else {
            // set logging level to INFO
            configureLogging(context, configFolder);
            return;
        }
    }
    // does a specific folder exist for this servlet context?
    if (servletContextName == null) {
        logger.error("specify display-name element in web.xml !!! ");
    } else {
        File specificFolder = new File(configFolder, servletContextName);
        if (specificFolder.exists() && specificFolder.isDirectory()) {
            configFolder = specificFolder;
        }
    }
    logger.info("loading configuration from folder {}", configFolder);
    configureLogging(context, configFolder);
    final XMLConfiguration config = createXMLConfiguration(context);
    File applicationConfigFile = new File(configFolder, "config.xml");
    if (!applicationConfigFile.exists()) {
        logger.warn("missing application config file {}", applicationConfigFile);
        loadDefaultConfiguration(config, applicationConfigFile);
    } else {
        try {
            config.load(applicationConfigFile);
            logger.info("parsed {}", applicationConfigFile);
        } catch (ConfigurationException e) {
            logger.error("Could not load configuration from {}", applicationConfigFile, e);
            loadDefaultConfiguration(config, null);
        }
    }
    context.setAttribute("config", config);
    logger.info("config now availabe via the following line of code\n"
            + "    XMLConfiguration appConfig = (XMLConfiguration) servletContext.getAttribute(\"config\");");

    logger.info("Starting up {}", servletContextName);
}

From source file:org.wso2.carbon.apimgt.webapp.publisher.APIPublisherUtil.java

/**
 * Build the API Configuration to be passed to APIM, from a given list of URL templates
 *
 * @param servletContext//from w ww.  j a  v  a  2 s  . com
 * @param apiDef
 * @return
 */
public static APIConfig buildApiConfig(ServletContext servletContext, APIResourceConfiguration apiDef)
        throws UserStoreException {
    APIConfig apiConfig = new APIConfig();

    String name = apiDef.getName();
    if (name == null || name.isEmpty()) {
        if (log.isDebugEnabled()) {
            log.debug("API Name not set in @SwaggerDefinition Annotation");
        }
        name = servletContext.getServletContextName();
    }
    apiConfig.setName(name);

    String version = apiDef.getVersion();
    if (version == null || version.isEmpty()) {
        if (log.isDebugEnabled()) {
            log.debug("'API Version not set in @SwaggerDefinition Annotation'");
        }
        version = API_CONFIG_DEFAULT_VERSION;
    }
    apiConfig.setVersion(version);

    String context = apiDef.getContext();
    if (context == null || context.isEmpty()) {
        if (log.isDebugEnabled()) {
            log.debug("'API Context not set in @SwaggerDefinition Annotation'");
        }
        context = servletContext.getContextPath();
    }
    apiConfig.setContext(context);

    String[] tags = apiDef.getTags();
    if (tags == null || tags.length == 0) {
        if (log.isDebugEnabled()) {
            log.debug("'API tag not set in @SwaggerDefinition Annotation'");
        }
    } else {
        apiConfig.setTags(tags);
    }

    String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain();
    servletContext.setAttribute(PARAM_PROVIDER_TENANT_DOMAIN, tenantDomain);
    tenantDomain = (tenantDomain != null && !tenantDomain.isEmpty()) ? tenantDomain
            : MultitenantConstants.SUPER_TENANT_DOMAIN_NAME;
    apiConfig.setTenantDomain(tenantDomain);

    String endpoint = servletContext.getInitParameter(PARAM_MANAGED_API_ENDPOINT);
    if (endpoint == null || endpoint.isEmpty()) {
        if (log.isDebugEnabled()) {
            log.debug("'managed-api-endpoint' attribute is not configured");
        }
        String endpointContext = apiDef.getContext();
        endpoint = APIPublisherUtil.getApiEndpointUrl(endpointContext);
    }
    apiConfig.setEndpoint(endpoint);

    String owner = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUserRealm().getRealmConfiguration()
            .getAdminUserName();
    if (!MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
        owner = owner + "@" + tenantDomain;
    }
    if (owner == null || owner.isEmpty()) {
        if (log.isDebugEnabled()) {
            log.debug("'managed-api-owner' attribute is not configured");
        }
    }
    apiConfig.setOwner(owner);

    apiConfig.setSecured(false);

    boolean isDefault = true;
    String isDefaultParam = servletContext.getInitParameter(PARAM_IS_DEFAULT);
    if (isDefaultParam != null && !isDefaultParam.isEmpty()) {
        isDefault = Boolean.parseBoolean(isDefaultParam);
    }
    apiConfig.setDefault(isDefault);

    String transports = servletContext.getInitParameter(PARAM_MANAGED_API_TRANSPORTS);
    if (transports == null || transports.isEmpty()) {
        if (log.isDebugEnabled()) {
            log.debug("'managed-api-transports' attribute is not configured. Therefore using the default, "
                    + "which is 'https'");
        }
        transports = "https,http";
    }
    apiConfig.setTransports(transports);

    String sharingValueParam = servletContext.getInitParameter(PARAM_SHARED_WITH_ALL_TENANTS);
    boolean isSharedWithAllTenants = Boolean.parseBoolean(sharingValueParam);
    if (isSharedWithAllTenants && !MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
        isSharedWithAllTenants = false;
    }
    apiConfig.setSharedWithAllTenants(isSharedWithAllTenants);

    Set<ApiUriTemplate> uriTemplates = new LinkedHashSet<>();
    for (APIResource apiResource : apiDef.getResources()) {
        ApiUriTemplate template = new ApiUriTemplate();
        template.setAuthType(apiResource.getAuthType());
        template.setHttpVerb(apiResource.getHttpVerb());
        template.setResourceURI(apiResource.getUri());
        template.setUriTemplate(apiResource.getUriTemplate());
        template.setScope(apiResource.getScope());
        uriTemplates.add(template);
    }
    apiConfig.setUriTemplates(uriTemplates);
    // adding scopes to the api
    Map<String, ApiScope> apiScopes = new HashMap<>();
    if (uriTemplates != null) {
        // this creates distinct scopes list
        for (ApiUriTemplate template : uriTemplates) {
            ApiScope scope = template.getScope();
            if (scope != null) {
                if (apiScopes.get(scope.getKey()) == null) {
                    apiScopes.put(scope.getKey(), scope);
                }
            }
        }
        Set<ApiScope> scopes = new HashSet<>(apiScopes.values());
        // set current scopes to API
        apiConfig.setScopes(scopes);
    }

    String policy = servletContext.getInitParameter(PARAM_MANAGED_API_POLICY);
    if (policy == null || policy.isEmpty()) {
        if (log.isDebugEnabled()) {
            log.debug("'managed-api-policy' attribute is not configured. Therefore using the default, "
                    + "which is 'null'");
        }
        policy = null;
    }
    apiConfig.setPolicy(policy);

    return apiConfig;
}

From source file:org.xz.qstruts.views.velocity.VelocityManager.java

/**
 * This method is responsible for creating the standard VelocityContext used by all WW2 velocity views.  The
 * following context parameters are defined:
 * <p/>//from w ww  .  java 2  s .  c o  m
 * <ul>
 * <li><strong>request</strong> - the current HttpServletRequest</li>
 * <li><strong>response</strong> - the current HttpServletResponse</li>
 * <li><strong>stack</strong> - the current {@link ValueStack}</li>
 * <li><strong>ognl</strong> - an {@link OgnlTool}</li>
 * <li><strong>struts</strong> - an instance of {@link org.apache.struts2.util.StrutsUtil}</li>
 * <li><strong>action</strong> - the current Struts action</li>
 * </ul>
 *
 * @return a new StrutsVelocityContext
 */
public Context createContext(ActionContext ac, HttpServletRequest req, HttpServletResponse res) {
    Context result = null;
    StrutsVelocityContext context = new StrutsVelocityContext(req);
    Map standardMap = ContextUtil.getStandardContext(ac, req, res);
    for (Iterator iterator = standardMap.entrySet().iterator(); iterator.hasNext();) {
        Map.Entry entry = (Map.Entry) iterator.next();
        context.put((String) entry.getKey(), entry.getValue());
    }

    ServletContext ctx = null;
    try {
        ctx = ServletActionContext.getServletContext();
        context.put("ctx", ctx.getServletContextName());
    } catch (NullPointerException npe) {
        // in case this was used outside the lifecycle of struts servlet
        LOG.debug("internal toolbox context ignored");
    }

    if (toolboxManager != null && ctx != null) {
        ChainedContext chained = new ChainedContext(context, velocityEngine, req, res, ctx);
        chained.setToolbox(toolboxManager.getToolbox(chained));
        result = chained;
    } else {
        result = context;
    }

    req.setAttribute(KEY_VELOCITY_STRUTS_CONTEXT, result);
    return result;
}

From source file:wicket.protocol.http.MockWebApplication.java

@Override
protected void init() {
    ServletContext context = getServletContext();
    servletSession = new MockHttpSession(context);
    servletRequest = new MockHttpServletRequest(this, servletSession, context);
    servletResponse = new MockHttpServletResponse();
    wicketRequest = newWebRequest(servletRequest);
    wicketSession = getSession(wicketRequest);

    // set the default context path
    getApplicationSettings().setContextPath(context.getServletContextName());

    getRequestCycleSettings().setRenderStrategy(RenderStrategy.ONE_PASS_RENDER);
    getResourceSettings().setResourceFinder(new WebApplicationPath(context));
    getPageSettings().setAutomaticMultiWindowSupport(false);
    getResourceSettings().setResourcePollFrequency(null);

    getDebugSettings().setSerializeSessionAttributes(false);

    createRequestCycle();//from  w  ww.ja v a 2  s  . com
}