Example usage for javax.servlet ServletContext getServerInfo

List of usage examples for javax.servlet ServletContext getServerInfo

Introduction

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

Prototype

public String getServerInfo();

Source Link

Document

Returns the name and version of the servlet container on which the servlet is running.

Usage

From source file:ServerSnoop.java

public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
    res.setContentType("text/plain");
    PrintWriter out = res.getWriter();

    ServletContext context = getServletContext();
    out.println("req.getServerName(): " + req.getServerName());
    out.println("req.getServerPort(): " + req.getServerPort());
    out.println("context.getServerInfo(): " + context.getServerInfo());
    out.println("getServerInfo() name: " + getServerInfoName(context.getServerInfo()));
    out.println("getServerInfo() version: " + getServerInfoVersion(context.getServerInfo()));
    out.println("context.getAttributeNames():");
    Enumeration e = context.getAttributeNames();
    while (e.hasMoreElements()) {
        String name = (String) e.nextElement();
        out.println("  context.getAttribute(\"" + name + "\"): " + context.getAttribute(name));
    }/* w ww  . j  a va  2s  .c o  m*/
}

From source file:org.phenotips.pingback.internal.client.data.ServletContainerPingDataProvider.java

@Override
public Map<String, Object> provideData() {
    Map<String, Object> jsonMap = new HashMap<>();
    if (this.environment instanceof ServletEnvironment) {
        ServletEnvironment servletEnvironment = (ServletEnvironment) this.environment;
        try {/* w w w.  ja  v  a2s .  c  om*/
            ServletContext servletContext = servletEnvironment.getServletContext();
            // Format of getServerInfo() is "name/version (text)" where " (text)" is optional.
            String serverInfo = servletContext.getServerInfo();
            jsonMap.put(PROPERTY_SERVLET_CONTAINER_NAME,
                    StringUtils.trim(StringUtils.substringBefore(serverInfo, SERVLET_INFO_VERSION_SEPARATOR)));
            jsonMap.put(PROPERTY_SERVLET_CONTAINER_VERSION,
                    StringUtils.trim(StringUtils.substringBefore(
                            StringUtils.substringAfter(serverInfo, SERVLET_INFO_VERSION_SEPARATOR),
                            SERVLET_INFO_OPTIONALSEPARATOR)));
        } catch (Throwable e) {
            // Ignore, we just don't save that information...
            // However we log a warning since it's a problem that needs to be seen and looked at.
            this.logger.warn("Failed to compute Servlet container information. "
                    + "This information has not been added to the Active Installs ping data. Reason [{}]",
                    ExceptionUtils.getRootCauseMessage(e), e);
        }
    }
    return jsonMap;
}

From source file:org.xwiki.activeinstalls.internal.client.data.ServletContainerPingDataProvider.java

@Override
public Map<String, Object> provideData() {
    Map<String, Object> jsonMap = new HashMap<>();
    if (this.environment instanceof ServletEnvironment) {
        ServletEnvironment servletEnvironment = (ServletEnvironment) this.environment;
        try {//from ww w  .  j  a  v a2 s .com
            ServletContext servletContext = servletEnvironment.getServletContext();
            // Format of getServerInfo() is "name/version (text)" where " (text)" is optional.
            String serverInfo = servletContext.getServerInfo();
            jsonMap.put(PROPERTY_SERVLET_CONTAINER_NAME,
                    StringUtils.trim(StringUtils.substringBefore(serverInfo, SERVLET_INFO_VERSION_SEPARATOR)));
            jsonMap.put(PROPERTY_SERVLET_CONTAINER_VERSION,
                    StringUtils.trim(StringUtils.substringBefore(
                            StringUtils.substringAfter(serverInfo, SERVLET_INFO_VERSION_SEPARATOR),
                            SERVLET_INFO_OPTIONALSEPARATOR)));
        } catch (Throwable e) {
            // Ignore, we just don't save that information...
            // However we log a warning since it's a problem that needs to be seen and looked at.
            this.logger.warn("Failed to compute Servlet container information. "
                    + "This information has not been added to the Active Installs ping data. Reason [{}]",
                    ExceptionUtils.getRootCauseMessage(e));
        }
    }
    return jsonMap;
}

From source file:com.devnexus.ting.web.WebAppInitializer.java

public void setupContext(final ServletContext servletContext) {

    final String contextPath = "";
    final String server = servletContext.getServerInfo();

    final Apphome apphome = SystemInformationUtils.retrieveBasicSystemInformation();

    final String outMessage;
    SpringContextMode springContextMode = null;

    switch (apphome.getAppHomeSource()) {

    case SYSTEM_PROPERTY:
        outMessage = "System Property '" + Apphome.APP_HOME_DIRECTORY + "' found: " + apphome.getAppHomePath();
        break;/*from   w w w.j  a  v a2s  .  com*/

    case ENVIRONMENT_VARIABLE:
        System.setProperty(Apphome.APP_HOME_DIRECTORY, apphome.getAppHomePath());

        outMessage = "Environment Variable '" + Apphome.APP_HOME_DIRECTORY + "' found: "
                + apphome.getAppHomePath() + ". Using it to set system property.";
        break;

    case USER_DIRECTORY:

        outMessage = "'" + Apphome.APP_HOME_DIRECTORY + "' not found. Please set '" + Apphome.APP_HOME_DIRECTORY
                + "' as a system property or as an environment variable. DEMO Mode, using embedded database.";
        break;
    case CLOUD:
        outMessage = "You are running in the cloud (CloudFoundry). No file system access available.";
        break;
    default:
        throw new IllegalStateException("Was expecting to resolve a home directory.");

    }

    if (SystemInformationUtils.existsConfigFile(apphome.getAppHomePath())) {
        springContextMode = SpringContextMode.ProductionContextConfiguration;
    } else {
        springContextMode = SpringContextMode.DemoContextConfiguration;
    }

    System.setProperty("ting-spring-profile", springContextMode.getCode());

    final StringBuilder bootMessage = new StringBuilder();

    bootMessage.append("\n");
    bootMessage.append(outMessage);
    bootMessage.append("\n");
    bootMessage.append("Using Spring Context: " + springContextMode);
    bootMessage.append("\n");
    bootMessage.append("Booting Ting...                          ").append("\n");
    bootMessage.append("-----------------------------------------------").append("\n");

    final String contextPathLabel = StringUtils.rightPad("Context Path", 40, '.');
    final String serverLabel = StringUtils.rightPad("Server", 40, '.');

    bootMessage.append(contextPathLabel + ": " + contextPath).append("\n");
    bootMessage.append(serverLabel + ": " + server).append("\n");

    bootMessage.append(SystemInformationUtils.getAllSystemProperties());
    bootMessage.append("-----------------------------------------------").append("\n");

    LOGGER.info(bootMessage.toString());
}

From source file:org.apache.wiki.ui.WikiJSPFilter.java

/** {@inheritDoc} */
public void init(FilterConfig config) throws ServletException {
    super.init(config);
    m_wiki_encoding = m_engine.getWikiProperties().getProperty(WikiEngine.PROP_ENCODING);
    ServletContext context = config.getServletContext();
    m_useOutputStream = UtilJ2eeCompat.useOutputStream(context.getServerInfo());
}

From source file:eu.openanalytics.rsb.component.SystemHealthResource.java

@GET
@Path("/info")
@Produces({ Constants.RSB_XML_CONTENT_TYPE, Constants.RSB_JSON_CONTENT_TYPE })
public NodeInformation getInfo(@Context final ServletContext sc) {
    final NodeInformation info = Util.REST_OBJECT_FACTORY.createNodeInformation();

    info.setName(getConfiguration().getNodeName());
    info.setHealthy(nodeHealthy.get());//from  w ww  .  j a  va2  s .c o  m
    info.setRsbVersion(getClass().getPackage().getImplementationVersion());
    info.setServletContainerInfo(sc.getServerInfo());

    final OperatingSystemMXBean operatingSystemMXBean = ManagementFactory.getOperatingSystemMXBean();
    info.setOsLoadAverage(operatingSystemMXBean.getSystemLoadAverage());

    final Runtime runtime = Runtime.getRuntime();
    info.setJvmMaxMemory(runtime.maxMemory());
    info.setJvmFreeMemory(runtime.freeMemory());

    final RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean();
    final long uptimeMilliseconds = runtimeMXBean.getUptime();
    info.setUptime(uptimeMilliseconds);
    info.setUptimeText(DurationFormatUtils.formatDurationWords(uptimeMilliseconds, true, true));

    return info;
}

From source file:com.icesoft.faces.util.event.servlet.ContextEventRepeater.java

/**
 * Fires a new <code>ContextDestroyedEvent</code>, based on the received
 * <code>event</code>, to all registered listeners, and cleans itself
 * up. </p>//  w  w w  . j ava 2 s  .c o m
 *
 * @param event the servlet context event.
 */
public void contextDestroyed(final ServletContextEvent event) {
    SessionDispatcherListener.contextDestroyed(event);
    ContextDestroyedEvent contextDestroyedEvent = new ContextDestroyedEvent(event);
    synchronized (LISTENERS) {
        Iterator _listeners = LISTENERS.keySet().iterator();
        while (_listeners.hasNext()) {
            ((ContextEventListener) _listeners.next()).contextDestroyed(contextDestroyedEvent);
        }
        LISTENERS.clear();
        synchronized (BUFFERED_CONTEXT_EVENTS) {
            BUFFERED_CONTEXT_EVENTS.clear();
        }
    }
    if (LOG.isInfoEnabled()) {
        ServletContext servletContext = contextDestroyedEvent.getServletContext();
        LOG.info("Servlet Context Name: " + servletContext.getServletContextName() + ", " + "Server Info: "
                + servletContext.getServerInfo());
    }
}

From source file:net.centro.rtb.monitoringcenter.MonitoringCenterServlet.java

@Override
public void init(ServletConfig servletConfig) throws ServletException {
    super.init(servletConfig);

    boolean disableAuthorization = Boolean.TRUE.toString()
            .equalsIgnoreCase(servletConfig.getInitParameter(DISABLE_AUTHORIZATION_INIT_PARAM));
    if (!disableAuthorization) {
        String credentials = null;

        String username = servletConfig.getInitParameter(USERNAME_INIT_PARAM);
        String password = servletConfig.getInitParameter(PASSWORD_INIT_PARAM);
        if (StringUtils.isNotBlank(username) && StringUtils.isNotBlank(password)) {
            credentials = username.trim() + ":" + password.trim();
        } else {/*from   w w  w.jav  a2 s  .c  om*/
            credentials = DEFAULT_CREDENTIALS;
        }

        this.encodedCredentials = BaseEncoding.base64().encode(credentials.getBytes());
    }

    this.objectMapper = new ObjectMapper()
            .registerModule(new MetricsModule(TimeUnit.SECONDS, TimeUnit.MICROSECONDS, false))
            .registerModule(new HealthCheckModule()).setSerializationInclusion(JsonInclude.Include.NON_NULL)
            .setTimeZone(TimeZone.getDefault()).setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z"));

    this.graphiteMetricFormatter = new GraphiteMetricFormatter(TimeUnit.SECONDS, TimeUnit.MICROSECONDS);

    try {
        this.threadDumpGenerator = new ThreadDump(ManagementFactory.getThreadMXBean());
    } catch (NoClassDefFoundError ignore) {
    }

    ServletContext servletContext = servletConfig.getServletContext();
    String servletSpecVersion = servletContext.getMajorVersion() + "." + servletContext.getMinorVersion();
    this.serverInfo = ServerInfo.create(servletContext.getServerInfo(), servletSpecVersion);
}

From source file:nl.nn.adapterframework.pipes.CreateRestViewPipe.java

private Map retrieveParameters(HttpServletRequest httpServletRequest, ServletContext servletContext,
        String srcPrefix) throws DomBuilderException {
    String attributeKey = AppConstants.getInstance().getProperty(ConfigurationServlet.KEY_CONTEXT);
    IbisContext ibisContext = (IbisContext) servletContext.getAttribute(attributeKey);
    Map parameters = new Hashtable();
    String requestInfoXml = "<requestInfo>" + "<servletRequest>" + "<serverInfo><![CDATA["
            + servletContext.getServerInfo() + "]]></serverInfo>" + "<serverName>"
            + httpServletRequest.getServerName() + "</serverName>" + "</servletRequest>" + "</requestInfo>";
    parameters.put("requestInfo", XmlUtils.buildNode(requestInfoXml));
    parameters.put("upTime", XmlUtils.buildNode("<upTime>" + ibisContext.getUptime() + "</upTime>"));
    String machineNameXml = "<machineName>" + Misc.getHostname() + "</machineName>";
    parameters.put("machineName", XmlUtils.buildNode(machineNameXml));
    String fileSystemXml = "<fileSystem>" + "<totalSpace>" + Misc.getFileSystemTotalSpace() + "</totalSpace>"
            + "<freeSpace>" + Misc.getFileSystemFreeSpace() + "</freeSpace>" + "</fileSystem>";
    parameters.put("fileSystem", XmlUtils.buildNode(fileSystemXml));
    String applicationConstantsXml = appConstants.toXml(true);
    parameters.put("applicationConstants", XmlUtils.buildNode(applicationConstantsXml));
    String processMetricsXml = ProcessMetrics.toXml();
    parameters.put("processMetrics", XmlUtils.buildNode(processMetricsXml));
    parameters.put("menuBar", XmlUtils.buildNode(retrieveMenuBarParameter(srcPrefix)));
    parameters.put(SRCPREFIX, srcPrefix);

    return parameters;
}

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());
    }//  ww w.  j av  a  2  s .co m
    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("/");
}