Example usage for javax.servlet ServletContext getContextPath

List of usage examples for javax.servlet ServletContext getContextPath

Introduction

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

Prototype

public String getContextPath();

Source Link

Document

Returns the context path of the web application.

Usage

From source file:org.jasig.portal.portlet.container.services.LocalPortletContextManager.java

/**
 * Retrieves the PortletContext associated with the given ServletContext.
 * If one does not exist, it is created.
 *
 * @param config the servlet config./*from   w  w w .  ja  v  a 2s.  co  m*/
 * @return the InternalPortletContext associated with the ServletContext.
 * @throws PortletContainerException
 */
@Override
public synchronized String register(ServletConfig config) throws PortletContainerException {
    ServletContext servletContext = config.getServletContext();
    String contextPath = servletContext.getContextPath();
    if (!portletContexts.containsKey(contextPath)) {

        PortletApplicationDefinition portletApp = this.getPortletAppDD(servletContext, contextPath,
                contextPath);

        DriverPortletContext portletContext = new DriverPortletContextImpl(servletContext, portletApp,
                requestDispatcherService);

        portletContexts.put(contextPath, portletContext);

        fireRegistered(portletContext);

        if (logger.isInfoEnabled()) {
            logger.info("Registered portlet application for context '" + contextPath + "'");

            logger.info("Registering " + portletApp.getPortlets().size() + " portlets for context "
                    + portletContext.getApplicationName());
        }

        //TODO have the portlet servlet provide the portlet's classloader as parameter to this method
        //This approach is needed as all pluto callbacks in uPortal have an aspect that switches the thread classloader back
        //to uPortal's classloader.
        ClassLoader classLoader = ThreadContextClassLoaderAspect.getPreviousClassLoader();
        if (classLoader == null) {
            classLoader = Thread.currentThread().getContextClassLoader();
        }
        classLoaders.put(portletApp.getName(), classLoader);
        for (PortletDefinition portlet : portletApp.getPortlets()) {
            String appName = portletContext.getApplicationName();
            if (appName == null) {
                throw new PortletContainerException("Portlet application name should not be null.");
            }
            portletConfigs.put(portletContext.getApplicationName() + "/" + portlet.getPortletName(),
                    new DriverPortletConfigImpl(portletContext, portlet));
        }
    } else {
        if (logger.isInfoEnabled()) {
            logger.info("Portlet application for context '" + contextPath + "' already registered.");
        }
    }
    return contextPath;
}

From source file:org.alfresco.bm.web.WebApp.java

@Override
public void onStartup(ServletContext container) {
    // Grab the server capabilities, otherwise just use the java version
    String javaVersion = System.getProperty("java.version");
    String systemCapabilities = System.getProperty(PROP_SYSTEM_CAPABILITIES, javaVersion);

    String appDir = new File(".").getAbsolutePath();
    String appContext = container.getContextPath();
    String appName = container.getContextPath().replace(SEPARATOR, "");

    // Create an application context (don't start, yet)
    XmlWebApplicationContext ctx = new XmlWebApplicationContext();
    ctx.setConfigLocations(new String[] { "classpath:config/spring/app-context.xml" });

    // Pass our properties to the new context
    Properties ctxProperties = new Properties();
    {/* w w  w.j ava  2 s  . co  m*/
        ctxProperties.put(PROP_SYSTEM_CAPABILITIES, systemCapabilities);
        ctxProperties.put(PROP_APP_CONTEXT_PATH, appContext);
        ctxProperties.put(PROP_APP_DIR, appDir);
    }
    ConfigurableEnvironment ctxEnv = ctx.getEnvironment();
    ctxEnv.getPropertySources().addFirst(new PropertiesPropertySource(appName, ctxProperties));
    // Override all properties with system properties
    ctxEnv.getPropertySources().addFirst(new PropertiesPropertySource("system", System.getProperties()));
    // Bind to shutdown
    ctx.registerShutdownHook();

    ContextLoaderListener ctxLoaderListener = new ContextLoaderListener(ctx);
    container.addListener(ctxLoaderListener);

    ServletRegistration.Dynamic jerseyServlet = container.addServlet("jersey-serlvet", SpringServlet.class);
    jerseyServlet.setInitParameter("com.sun.jersey.config.property.packages", "org.alfresco.bm.rest");
    jerseyServlet.setInitParameter("com.sun.jersey.api.json.POJOMappingFeature", "true");
    jerseyServlet.addMapping("/api/*");
}

From source file:org.apereo.portal.portlet.container.services.LocalPortletContextManager.java

/**
 * Retrieves the PortletContext associated with the given ServletContext.
 * If one does not exist, it is created.
 *
 * @param config the servlet config.//from w w w .  j  a v  a 2 s .co  m
 * @return the InternalPortletContext associated with the ServletContext.
 * @throws PortletContainerException
 */
@Override
public synchronized String register(ServletConfig config) throws PortletContainerException {
    ServletContext servletContext = config.getServletContext();
    String contextPath = servletContext.getContextPath();
    if (!portletContexts.containsKey(contextPath)) {

        PortletApplicationDefinition portletApp = this.getPortletAppDD(servletContext, contextPath,
                contextPath);

        DriverPortletContext portletContext = new DriverPortletContextImpl(servletContext, portletApp,
                requestDispatcherService);

        portletContext.setAttribute(PlatformApiBroker.PORTLET_CONTEXT_ATTRIBUTE_NAME, platformApiBroker);
        portletContexts.put(contextPath, portletContext);

        fireRegistered(portletContext);

        if (logger.isInfoEnabled()) {
            logger.info("Registered portlet application for context '" + contextPath + "'");

            logger.info("Registering " + portletApp.getPortlets().size() + " portlets for context "
                    + portletContext.getApplicationName());
        }

        //TODO have the portlet servlet provide the portlet's classloader as parameter to this method
        //This approach is needed as all pluto callbacks in uPortal have an aspect that switches the thread classloader back
        //to uPortal's classloader.
        ClassLoader classLoader = ThreadContextClassLoaderAspect.getPreviousClassLoader();
        if (classLoader == null) {
            classLoader = Thread.currentThread().getContextClassLoader();
        }
        classLoaders.put(portletApp.getName(), classLoader);
        for (PortletDefinition portlet : portletApp.getPortlets()) {
            String appName = portletContext.getApplicationName();
            if (appName == null) {
                throw new PortletContainerException("Portlet application name should not be null.");
            }
            portletConfigs.put(portletContext.getApplicationName() + "/" + portlet.getPortletName(),
                    new DriverPortletConfigImpl(portletContext, portlet));
        }
    } else {
        if (logger.isInfoEnabled()) {
            logger.info("Portlet application for context '" + contextPath + "' already registered.");
        }
    }
    return contextPath;
}

From source file:com.jsmartframework.web.util.WebImage.java

public void init(ServletContext servletContext) {
    if (contextPath == null) {
        contextPath = "";
        String assetsUrl = CONFIG.getContent().getAssetsUrl();

        if (StringUtils.isNotBlank(assetsUrl)) {
            contextPath = assetsUrl.endsWith("/") ? assetsUrl.substring(0, assetsUrl.length() - 1) : assetsUrl;
        } else if (StringUtils.isNotBlank(servletContext.getContextPath())) {
            contextPath = servletContext.getContextPath();
        }/* w  w w.  j  a  v a2s  . c o  m*/
    }
}

From source file:nl.armatiek.xslweb.configuration.Context.java

public void setServletContext(ServletContext servletContext) {
    this.servletContext = servletContext;
    this.contextPath = servletContext.getContextPath();
    this.webInfDir = new File(servletContext.getRealPath("/WEB-INF"));
}

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   ww  w  .j av a  2s . co  m
 * @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:io.fabric8.api.registry.ApiRegistryService.java

protected void checkForUrlPrefix() {
    if (urlPrefix == null && messageContext != null) {
        HttpServletRequest request = messageContext.getHttpServletRequest();
        ServletContext servletContext = messageContext.getServletContext();
        if (request != null && servletContext != null) {
            String swaggerPrefix = request.getScheme() + "://" + request.getServerName() + ":"
                    + request.getServerPort();
            String contextPath = servletContext.getContextPath();
            urlPrefix = urlPathJoin(swaggerPrefix, contextPath);
            finder.setUrlPrefix(urlPrefix);
        }//from ww w.ja va 2s .  co m
    }

}

From source file:org.red5.server.war.RootContextLoaderServlet.java

public void registerSubContext(String webAppKey) {
    // get the sub contexts - servlet context
    ServletContext ctx = servletContext.getContext(webAppKey);
    logger.info("Registering subcontext for servlet context: " + ctx.getContextPath());
    if (registeredContexts.contains(ctx)) {
        logger.debug("Context is already registered: " + webAppKey);
        return;/*from   www. j av a  2s .c  o m*/
    }

    ContextLoader loader = new ContextLoader();

    ConfigurableWebApplicationContext appCtx = (ConfigurableWebApplicationContext) loader
            .initWebApplicationContext(ctx);
    appCtx.setParent(applicationContext);
    appCtx.refresh();

    ctx.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, appCtx);

    ConfigurableBeanFactory appFactory = appCtx.getBeanFactory();

    logger.debug("About to grab Webcontext bean for " + webAppKey);
    Context webContext = (Context) appCtx.getBean("web.context");
    webContext.setCoreBeanFactory(parentFactory);
    webContext.setClientRegistry(clientRegistry);
    webContext.setServiceInvoker(globalInvoker);
    webContext.setScopeResolver(globalResolver);
    webContext.setMappingStrategy(globalStrategy);

    WebScope scope = (WebScope) appFactory.getBean("web.scope");
    scope.setServer(server);
    scope.setParent(global);
    scope.register();
    scope.start();

    // register the context so we dont try to reinitialize it
    registeredContexts.add(ctx);

}

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 w w.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.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 {/* w ww  .j  a v a2 s .  c  om*/
            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);
}