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:com.dominion.salud.nomenclator.configuration.NOMENCLATORInitializer.java

@Override
public void onStartup(ServletContext servletContext) throws ServletException {
    AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
    ctx.scan("com.dominion.salud.nomenclator.configuration");
    ctx.setServletContext(servletContext);
    ctx.refresh();/* ww  w.  j  a v a2  s .  c  o  m*/

    logger.info("     Registrando servlets de configuracion");
    ServletRegistration.Dynamic dispatcher = servletContext.addServlet("dispatcher",
            new DispatcherServlet(ctx));
    dispatcher.setInitParameter("contextClass", ctx.getClass().getName());
    dispatcher.setLoadOnStartup(1);
    logger.info("          Agregando mapping: /");
    dispatcher.addMapping("/");
    logger.info("          Agregando mapping: /controller/*");
    dispatcher.addMapping("/controller/*");
    logger.info("          Agregando mapping: /services/*");
    dispatcher.addMapping("/services/*");
    servletContext.addListener(new ContextLoaderListener(ctx));
    logger.info("     Servlets de configuracion registrados correctamente");

    // Configuracion general
    logger.info("     Iniciando la configuracion del modulo");
    NOMENCLATORConstantes._HOME = StringUtils.endsWith(servletContext.getRealPath("/"), File.separator)
            ? servletContext.getRealPath("/")
            : servletContext.getRealPath("/") + File.separator;
    NOMENCLATORConstantes._TEMP = NOMENCLATORConstantes._HOME + "WEB-INF" + File.separator + "temp"
            + File.separator;
    NOMENCLATORConstantes._VERSION = ResourceBundle.getBundle("version").getString("version");
    NOMENCLATORConstantes._LOGS = NOMENCLATORConstantes._HOME + "WEB-INF" + File.separator + "classes"
            + File.separator + "logs";
    NOMENCLATORConstantes._CONTEXT_NAME = servletContext.getServletContextName();
    NOMENCLATORConstantes._CONTEXT_PATH = servletContext.getContextPath();
    NOMENCLATORConstantes._CONTEXT_SERVER = servletContext.getServerInfo();
    NOMENCLATORConstantes._ENABLE_TECHNICAL_INFORMATION = StringUtils.isNotBlank(
            ResourceBundle.getBundle("application").getString("nomenclator.enable.technical.information"))
                    ? Boolean.parseBoolean(ResourceBundle.getBundle("application")
                            .getString("nomenclator.enable.technical.information"))
                    : false;
    PropertyConfigurator.configureAndWatch("log4j");

    logger.info("          Configuracion general del sistema");
    logger.info("               nomenclator.home: " + NOMENCLATORConstantes._HOME);
    logger.info("               nomenclator.temp: " + NOMENCLATORConstantes._TEMP);
    logger.info("               nomenclator.version: " + NOMENCLATORConstantes._VERSION);
    logger.info("               nomenclator.logs: " + NOMENCLATORConstantes._LOGS);
    logger.info("               nomenclator.context.name: " + NOMENCLATORConstantes._CONTEXT_NAME);
    logger.info("               nomenclator.context.path: " + NOMENCLATORConstantes._CONTEXT_PATH);
    logger.info("               nomenclator.context.server: " + NOMENCLATORConstantes._CONTEXT_SERVER);
    logger.info("          Parametrizacion del sistema");
    logger.info("               nomenclator.enable.technical.information: "
            + NOMENCLATORConstantes._ENABLE_TECHNICAL_INFORMATION);
    logger.info("     Modulo configurado correctamente");
    logger.info("MODULO INICIADO CORRECTAMENTE");
}

From source file:com.thruzero.common.jsf.utils.FacesUtils.java

public static String getServletContextName() {
    ServletContext ServletContext = (ServletContext) getExternalContext().getContext();

    return ServletContext.getServletContextName();
}

From source file:com.sun.faces.config.ConfigureListener.java

public void contextInitialized(ServletContextEvent sce) {
    // Prepare local variables we will need
    Digester digester = null;/*from w w w  .j av a 2 s.com*/
    FacesConfigBean fcb = new FacesConfigBean();
    ServletContext context = sce.getServletContext();

    // store the servletContext instance in Thread local Storage.
    // This enables our Application's ApplicationAssociate to locate
    // it so it can store the ApplicationAssociate in the
    // ServletContext.
    tlsExternalContext.set(new ServletContextAdapter(context));

    // see if we're operating in the unit test environment
    try {
        if (RIConstants.IS_UNIT_TEST_MODE) {
            // if so, put the fcb in the servletContext
            context.setAttribute(FACES_CONFIG_BEAN_KEY, fcb);
        }
    } catch (Exception e) {
        if (log.isDebugEnabled()) {
            log.debug("Can't query for test environment");
        }
    }

    // see if we need to disable our TLValidator
    RIConstants.HTML_TLV_ACTIVE = isFeatureEnabled(context, ENABLE_HTML_TLV);

    URL url = null;
    if (log.isDebugEnabled()) {
        log.debug("contextInitialized(" + context.getServletContextName() + ")");
    }

    // Ensure that we initialize a particular application ony once
    if (initialized()) {
        return;
    }

    // Step 1, configure a Digester instance we can use
    digester = digester(isFeatureEnabled(context, VALIDATE_XML));

    // Step 2, parse the RI configuration resource
    url = Util.getCurrentLoader(this).getResource(JSF_RI_CONFIG);
    parse(digester, url, fcb);

    // Step 3, parse any "/META-INF/faces-config.xml" resources
    Iterator resources;
    try {
        List list = new LinkedList();
        Enumeration items = Util.getCurrentLoader(this).getResources(META_INF_RESOURCES);
        while (items.hasMoreElements()) {
            list.add(0, items.nextElement());
        }
        resources = list.iterator();
    } catch (IOException e) {
        String message = null;
        try {
            message = Util.getExceptionMessageString(Util.CANT_PARSE_FILE_ERROR_MESSAGE_ID,
                    new Object[] { META_INF_RESOURCES });
        } catch (Exception ee) {
            message = "Can't parse configuration file:" + META_INF_RESOURCES;
        }
        log.warn(message, e);
        throw new FacesException(message, e);
    }
    while (resources.hasNext()) {
        url = (URL) resources.next();
        parse(digester, url, fcb);
    }

    // Step 4, parse any context-relative resources specified in
    // the web application deployment descriptor
    String paths = context.getInitParameter(FacesServlet.CONFIG_FILES_ATTR);
    if (paths != null) {
        for (StringTokenizer t = new StringTokenizer(paths.trim(), ","); t.hasMoreTokens();) {

            url = getContextURLForPath(context, t.nextToken().trim());
            if (url != null) {
                parse(digester, url, fcb);
            }

        }
    }

    // Step 5, parse "/WEB-INF/faces-config.xml" if it exists
    url = getContextURLForPath(context, WEB_INF_RESOURCE);
    if (url != null) {
        parse(digester, url, fcb);
    }

    // Step 6, use the accumulated configuration beans to configure the RI
    try {
        configure(context, fcb);
    } catch (FacesException e) {
        e.printStackTrace();
        throw e;
    } catch (Exception e) {
        e.printStackTrace();
        throw new FacesException(e);
    }

    // Step 7, verify that all the configured factories are available
    // and optionall that configured objects can be created
    verifyFactories();
    if (isFeatureEnabled(context, VERIFY_OBJECTS)) {
        verifyObjects(context, fcb);
    }

    tlsExternalContext.set(null);
}

From source file:net.bull.javamelody.internal.model.JavaInformations.java

public JavaInformations(ServletContext servletContext, boolean includeDetails) {
    // CHECKSTYLE:ON
    super();//from w  ww . ja  v a  2s  .  co  m
    memoryInformations = new MemoryInformations();
    tomcatInformationsList = TomcatInformations.buildTomcatInformationsList();
    sessionCount = SessionListener.getSessionCount();
    sessionAgeSum = SessionListener.getSessionAgeSum();
    activeThreadCount = JdbcWrapper.getActiveThreadCount();
    usedConnectionCount = JdbcWrapper.getUsedConnectionCount();
    activeConnectionCount = JdbcWrapper.getActiveConnectionCount();
    maxConnectionCount = JdbcWrapper.getMaxConnectionCount();
    transactionCount = JdbcWrapper.getTransactionCount();
    systemLoadAverage = buildSystemLoadAverage();
    systemCpuLoad = buildSystemCpuLoad();
    processCpuTimeMillis = buildProcessCpuTimeMillis();
    unixOpenFileDescriptorCount = buildOpenFileDescriptorCount();
    unixMaxFileDescriptorCount = buildMaxFileDescriptorCount();
    host = Parameters.getHostName() + '@' + Parameters.getHostAddress();
    os = buildOS();
    availableProcessors = Runtime.getRuntime().availableProcessors();
    javaVersion = System.getProperty("java.runtime.name") + ", " + System.getProperty("java.runtime.version");
    jvmVersion = System.getProperty("java.vm.name") + ", " + System.getProperty("java.vm.version") + ", "
            + System.getProperty("java.vm.info");
    if (servletContext == null) {
        serverInfo = null;
        contextPath = null;
        contextDisplayName = null;
        webappVersion = null;
    } else {
        serverInfo = servletContext.getServerInfo();
        contextPath = Parameters.getContextPath(servletContext);
        contextDisplayName = servletContext.getServletContextName();
        webappVersion = MavenArtifact.getWebappVersion();
    }
    startDate = START_DATE;
    jvmArguments = buildJvmArguments();
    final ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();
    threadCount = threadBean.getThreadCount();
    peakThreadCount = threadBean.getPeakThreadCount();
    totalStartedThreadCount = threadBean.getTotalStartedThreadCount();
    freeDiskSpaceInTemp = Parameters.TEMPORARY_DIRECTORY.getFreeSpace();
    springBeanExists = SPRING_AVAILABLE && SpringContext.getSingleton() != null;

    if (includeDetails) {
        dataBaseVersion = buildDataBaseVersion();
        dataSourceDetails = buildDataSourceDetails();
        threadInformationsList = buildThreadInformationsList();
        cacheInformationsList = CacheInformations.buildCacheInformationsList();
        jobInformationsList = JobInformations.buildJobInformationsList();
        pid = PID.getPID();
    } else {
        dataBaseVersion = null;
        dataSourceDetails = null;
        threadInformationsList = null;
        cacheInformationsList = null;
        jobInformationsList = null;
        pid = null;
    }
}

From source file:org.apache.hadoop.gateway.filter.rewrite.impl.UrlRewriteResponseTest.java

@Test
public void testResolve() throws Exception {

    UrlRewriteProcessor rewriter = EasyMock.createNiceMock(UrlRewriteProcessor.class);

    ServletContext context = EasyMock.createNiceMock(ServletContext.class);
    EasyMock.expect(context.getServletContextName()).andReturn("test-cluster-name").anyTimes();
    EasyMock.expect(context.getInitParameter("test-init-param-name")).andReturn("test-init-param-value")
            .anyTimes();/* w ww .  j av a 2  s.co  m*/
    EasyMock.expect(context.getAttribute(UrlRewriteServletContextListener.PROCESSOR_ATTRIBUTE_NAME))
            .andReturn(rewriter).anyTimes();

    FilterConfig config = EasyMock.createNiceMock(FilterConfig.class);
    EasyMock.expect(config.getInitParameter("test-filter-init-param-name"))
            .andReturn("test-filter-init-param-value").anyTimes();
    EasyMock.expect(config.getServletContext()).andReturn(context).anyTimes();

    HttpServletRequest request = EasyMock.createNiceMock(HttpServletRequest.class);
    HttpServletResponse response = EasyMock.createNiceMock(HttpServletResponse.class);

    EasyMock.replay(rewriter, context, config, request, response);

    UrlRewriteResponse rewriteResponse = new UrlRewriteResponse(config, request, response);

    List<String> names = rewriteResponse.resolve("test-filter-init-param-name");
    assertThat(names.size(), is(1));
    assertThat(names.get(0), is("test-filter-init-param-value"));
}

From source file:org.apache.hadoop.hdfsproxy.ProxyForwardServlet.java

/** {@inheritDoc} */
@Override/* w w w. j a va2  s .  c om*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    String hostname = request.getServerName();

    String version = configuration.get(hostname);
    if (version == null) {
        // extract from hostname directly
        String[] strs = hostname.split("[-\\.]");
        version = "/" + strs[0];
    }

    ServletContext curContext = getServletContext();
    ServletContext dstContext = curContext.getContext(version);

    // avoid infinite forwarding.
    if (dstContext == null || "HDFS Proxy Forward".equals(dstContext.getServletContextName())) {
        LOG.error("Context (" + version + ".war) non-exist or restricted from access");
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }
    LOG.debug("Request to " + hostname + " is forwarded to version " + version);
    forwardRequest(request, response, dstContext, request.getServletPath());

}

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

/**
 * Creates the portlet.xml deployment descriptor representation.
 *
 * @param servletContext  the servlet context for which the DD is requested.
 * @return the Portlet Application Deployment Descriptor.
 * @throws PortletContainerException/*w w w  . j a  v  a 2 s  .  c o m*/
 */
private PortletApplicationDefinition createDefinition(ServletContext servletContext, String name,
        String contextPath) throws PortletContainerException {
    PortletApplicationDefinition portletApp = null;
    try {
        InputStream paIn = servletContext.getResourceAsStream(PORTLET_XML);
        InputStream webIn = servletContext.getResourceAsStream(WEB_XML);
        if (paIn == null) {
            throw new PortletContainerException(
                    "Cannot find '" + PORTLET_XML + "'. Are you sure it is in the deployed package?");
        }
        if (webIn == null) {
            throw new PortletContainerException(
                    "Cannot find '" + WEB_XML + "'. Are you sure it is in the deployed package?");
        }
        portletApp = this.portletAppDescriptorService.read(name, contextPath, paIn);
        this.portletAppDescriptorService.mergeWebDescriptor(portletApp, webIn);
    } catch (Exception ex) {
        throw new PortletContainerException(
                "Exception loading portlet descriptor for: " + servletContext.getServletContextName(), ex);
    }
    return portletApp;
}

From source file:org.impalaframework.web.spring.WebappPropertyPlaceholderConfigurer.java

public String getWebContextName(ServletContext servletContext) {
    Assert.notNull(servletContext);/*from  w  w w  . j  a v a 2s  .  c  o  m*/
    String webContextName = servletContext.getInitParameter(WEBAPP_CONFIG_PROPERTY_NAME);

    if (webContextName == null) {
        logger.warn("web.xml for " + servletContext.getServletContextName()
                + " does not define the context parameter (using the element 'context-param' with name "
                + WEBAPP_CONFIG_PROPERTY_NAME + ")");
    }
    return webContextName;
}

From source file:org.mobicents.servlet.sip.restcomm.callmanager.mgcp.MgcpCallManager.java

@Override
public final void init(final ServletConfig config) throws ServletException {
    try {/*ww w.  j a  v  a2s  .co m*/
        final ServletContext context = config.getServletContext();
        LOGGER.info(
                "initializing the servlet with context:" + context + " ServerInfo:" + context.getServerInfo()
                        + " ServletContextName:" + context.getServletContextName() + " config:" + config);
        context.setAttribute("org.mobicents.servlet.sip.restcomm.callmanager.CallManager", this);
        try {
            Bootstrapper.bootstrap(config);
        } catch (final BootstrapException exception) {
            throw new ServletException(exception);
        }
        sipFactory = (SipFactory) config.getServletContext().getAttribute(SIP_FACTORY);
        final ServiceLocator services = ServiceLocator.getInstance();
        servers = services.get(MgcpServerManager.class);
        configuration = services.get(Configuration.class);
        proxyUser = configuration.getString("outbound-proxy-user");
        proxyPassword = configuration.getString("outbound-proxy-password");
        final String uri = configuration.getString("outbound-proxy-uri");
        if (uri != null && !uri.isEmpty()) {
            proxyUri = sipFactory.createSipURI(null, uri);
        }
        ///////////
        LOGGER.info("initializing jvoicexml inteface........");
        embJVXML = new EmbeddedJVXML();
        embJVXML.init();
        //        //init jvoicexml context
        //        contextJXML = new InitialContext();
        //        LOGGER.info("init jvoicexml context:contextJXML:"+contextJXML);
        //        
        //        //
        //        LOGGER.info("creating VoiceXML documents and binding to the applications.....");
        //        vxmlDocument = createVXMLDoc();
        //        printDocument(vxmlDocument);
        //        
        //        //
        //        LOGGER.info("adding VXML document to repository...");
        //        vxmlURI=addDocument(vxmlDocument);
        //        
    } catch (Exception e) {
        ExLog.exception(LOGGER, e);
    }
}

From source file:org.opensubsystems.core.util.servlet.WebUtils.java

/**
 * Create debug string containing all parameter names and their values from
 * the context./*w w w.  j  av  a  2s . c om*/
 *
 * @param  scContext - context to print out
 * @return String - debug string containing all parameter names and their
 *                  values from the context
 */
public static String debug(ServletContext scContext) {
    Enumeration enumNames;
    String strParam;
    StringBuilder sbfReturn = new StringBuilder();

    sbfReturn.append("ServletContext=[ServletContextName=");
    sbfReturn.append(scContext.getServletContextName());
    sbfReturn.append(";");
    for (enumNames = scContext.getInitParameterNames(); enumNames.hasMoreElements();) {
        strParam = (String) enumNames.nextElement();
        sbfReturn.append("Param=");
        sbfReturn.append(strParam);
        sbfReturn.append(" value=");
        sbfReturn.append(scContext.getInitParameter(strParam));
        if (enumNames.hasMoreElements()) {
            sbfReturn.append(";");
        }
    }
    sbfReturn.append("]");

    return sbfReturn.toString();
}