下面列出了javax.servlet.http.HttpSessionAttributeListener#javax.servlet.ServletContext 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Create a map from a ServletContext object
* @return The resulting Map
*/
public static Map<String, Object> getServletContextMap(HttpServletRequest request, Set<? extends String> namesToSkip) {
Map<String, Object> servletCtxMap = new HashMap<>();
// look at all servlet context attributes
ServletContext servletContext = request.getServletContext(); // SCIPIO: get context using servlet API 3.0
Enumeration<String> applicationAttrNames = UtilGenerics.cast(servletContext.getAttributeNames());
while (applicationAttrNames.hasMoreElements()) {
String attrName = applicationAttrNames.nextElement();
if (namesToSkip != null && namesToSkip.contains(attrName)) {
continue;
}
Object attrValue = servletContext.getAttribute(attrName);
servletCtxMap.put(attrName, attrValue);
}
if (Debug.verboseOn()) {
Debug.logVerbose("Made ServletContext Attribute Map with [" + servletCtxMap.size() + "] Entries", module);
Debug.logVerbose("ServletContext Attribute Map Entries: " + System.getProperty("line.separator") + UtilMisc.printMap(servletCtxMap), module);
}
return servletCtxMap;
}
@Before
public void init() throws ServletException {
pluginMonitoringFilter = new MyPluginMonitoringFilter();
final FilterConfig config = createNiceMock(FilterConfig.class);
final ServletContext context = createNiceMock(ServletContext.class);
expect(config.getServletContext()).andReturn(context).anyTimes();
// expect(config.getFilterName()).andReturn(FILTER_NAME).anyTimes();
expect(context.getMajorVersion()).andReturn(2).anyTimes();
expect(context.getMinorVersion()).andReturn(5).anyTimes();
expect(context.getContextPath()).andReturn(CONTEXT_PATH).anyTimes();
expect(context.getServerInfo()).andReturn("mockJetty").anyTimes();
replay(config);
replay(context);
pluginMonitoringFilter.init(config);
verify(config);
verify(context);
}
/**
* Initializes Spring and Spring MVC.
*/
private ServletRegistration.Dynamic initSpring(ServletContext servletContext, AnnotationConfigWebApplicationContext rootContext) {
LOGGER.debug("Configuring Spring Web application context");
AnnotationConfigWebApplicationContext dispatcherServletConfiguration = new AnnotationConfigWebApplicationContext();
dispatcherServletConfiguration.setParent(rootContext);
dispatcherServletConfiguration.register(DispatcherServletConfiguration.class);
LOGGER.debug("Registering Spring MVC Servlet");
ServletRegistration.Dynamic dispatcherServlet = servletContext.addServlet("dispatcher", new DispatcherServlet(dispatcherServletConfiguration));
dispatcherServlet.addMapping("/service/*");
dispatcherServlet.setMultipartConfig(new MultipartConfigElement((String) null));
dispatcherServlet.setLoadOnStartup(1);
dispatcherServlet.setAsyncSupported(true);
return dispatcherServlet;
}
@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();
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" ) );
}
/**
* {@inheritDoc}
*/
@Override
public void authenticate(HttpServletRequest request) throws AuthenticationException {
String userName = request.getRemoteUser();
userName = userName.substring(userName.indexOf("\\") + 1);
if (log.isDebugEnabled()) {
log.debug("Authenticate request received : Authtype - " + request.getAuthType() +
", User - " + userName);
}
ServletContext servletContext = request.getSession().getServletContext();
HttpSession session = request.getSession();
String backendServerURL = request.getParameter("backendURL");
if (backendServerURL == null) {
backendServerURL = CarbonUIUtil.getServerURL(servletContext, request.getSession());
}
session.setAttribute(CarbonConstants.SERVER_URL, backendServerURL);
String rememberMe = request.getParameter("rememberMe");
handleSecurity(userName, (rememberMe != null), request);
request.setAttribute("username", userName);
}
private void addDispatcherContext(ServletContext container) {
// Create the dispatcher servlet's Spring application context
AnnotationConfigWebApplicationContext dispatcherContext = new AnnotationConfigWebApplicationContext();
dispatcherContext.register(SpringDispatcherConfig.class);
// Declare <servlet> and <servlet-mapping> for the DispatcherServlet
ServletRegistration.Dynamic dispatcher = container.addServlet("ch03-servlet",
new DispatcherServlet(dispatcherContext));
dispatcher.addMapping("*.html");
dispatcher.setLoadOnStartup(1);
FilterRegistration.Dynamic corsFilter = container.addFilter("corsFilter", new CorsFilter());
corsFilter.setInitParameter("cors.allowed.methods", "GET, POST, HEAD, OPTIONS, PUT, DELETE");
corsFilter.addMappingForUrlPatterns(null, true, "/*");
FilterRegistration.Dynamic filter = container.addFilter("hiddenmethodfilter", new HiddenHttpMethodFilter());
filter.addMappingForServletNames(null, true, "/*");
FilterRegistration.Dynamic multipartFilter = container.addFilter("multipartFilter", new MultipartFilter());
multipartFilter.addMappingForUrlPatterns(null, true, "/*");
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
// Destroy any AtmosphereFramework instance we have initialized.
// This must be done here to ensure that we cleanup Atmosphere instances
// related to servlets which are never initialized
ServletContext servletContext = sce.getServletContext();
Enumeration<String> attributeNames = servletContext.getAttributeNames();
while (attributeNames.hasMoreElements()) {
String attributeName = attributeNames.nextElement();
if (isAtmosphereFrameworkAttribute(attributeName)) {
Object value = servletContext.getAttribute(attributeName);
if (value instanceof AtmosphereFramework) {
// This might result in calling destroy() twice, once from
// here and once from PushRequestHandler but
// AtmosphereFramework.destroy() deals with that
((AtmosphereFramework) value).destroy();
}
}
}
}
public void init(ServletConfig servletConfig) throws ServletException {
super.init(servletConfig);
ServletContext context = servletConfig.getServletContext();
String controllerClassName =
context.getInitParameter("InterfaceX_Service");
try {
Class controllerClass = Class.forName(controllerClassName);
// If the class has a getInstance() method, call that method rather than
// calling a constructor (& thus instantiating 2 instances of the class)
try {
Method instMethod = controllerClass.getDeclaredMethod("getInstance");
_controller = (InterfaceX_Service) instMethod.invoke(null);
}
catch (NoSuchMethodException nsme) {
_controller = (InterfaceX_Service) controllerClass.newInstance();
}
}
catch (Exception e) {
e.printStackTrace();
}
}
private void logServletCreation(VaadinServletCreation servletCreation,
ServletContext servletContext, boolean productionMode) {
Logger logger = getLogger();
if (servletCreation == null || productionMode) {
// the servlet creation is explicitly disabled or production mode
// activated - just info
logger.info(servletCreationMessage);
} else if (servletCreation == VaadinServletCreation.NO_CREATION) {
// debug mode and servlet not created for some reason - make it more
// visible with warning
logger.warn(servletCreationMessage);
} else {
logger.info(servletCreationMessage);
ServletRegistration vaadinServlet = findVaadinServlet(
servletContext);
logAppStartupToConsole(servletContext,
servletCreation == VaadinServletCreation.SERVLET_CREATED
|| vaadinServlet != null
&& "com.vaadin.cdi.CdiServletDeployer"
.equals(vaadinServlet.getName()));
}
}
@Override
public void contextInitialized(ServletContextEvent servletContextEvent) {
ServletContext context = servletContextEvent.getServletContext();
plugin = new HawtioPlugin();
plugin.setContext((String)context.getInitParameter("plugin-context"));
plugin.setName(context.getInitParameter("plugin-name"));
plugin.setScripts(context.getInitParameter("plugin-scripts"));
plugin.setDomain(null);
try {
plugin.init();
} catch (Exception e) {
throw createServletException(e);
}
LOG.info("Initialized {} plugin", plugin.getName());
}
@Override
public void onStartup(Set<Class<?>> c, ServletContext ctx)
throws ServletException {
// Register and map servlet
Servlet s = new TesterServlet();
ServletRegistration.Dynamic sr = ctx.addServlet("test", s);
sr.addMapping("/test");
// Add a constraint with uncovered methods
HttpConstraintElement hce = new HttpConstraintElement(
TransportGuarantee.NONE, "tomcat");
HttpMethodConstraintElement hmce =
new HttpMethodConstraintElement("POST", hce);
Set<HttpMethodConstraintElement> hmces = new HashSet<>();
hmces.add(hmce);
ServletSecurityElement sse = new ServletSecurityElement(hmces);
sr.setServletSecurity(sse);
}
@Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
final ServletContext context = config.getServletContext();
if (null == registry) {
final Object registryAttr = context.getAttribute(METRICS_REGISTRY);
if (registryAttr instanceof MetricRegistry) {
this.registry = (MetricRegistry) registryAttr;
} else {
throw new ServletException("Couldn't find a MetricRegistry instance.");
}
}
filter = (MetricFilter) context.getAttribute(METRIC_FILTER);
if (filter == null) {
filter = MetricFilter.ALL;
}
this.allowedOrigin = context.getInitParameter(ALLOWED_ORIGIN);
}
@Override
public ServletContext getServletContext()
{
if ( null == _servletContext )
{
_servletContext = mock( ServletContext.class );
}
return _servletContext;
}
private RequestLogEntry createLogEntry(String title) {
final ServletContext servletContext = (ServletContext) context
.getMessageContext().get(MessageContext.SERVLET_CONTEXT);
final RequestLog log = (RequestLog) servletContext
.getAttribute(InitServlet.REQUESTLOG);
final RequestLogEntry entry = log.createEntry(
ProvisioningService.class.getSimpleName() + "." + title,
RequestDirection.INBOUND);
ServletRequest request = (ServletRequest) context.getMessageContext()
.get(MessageContext.SERVLET_REQUEST);
entry.setHost(request.getRemoteHost());
return entry;
}
public ServletContext getServletContext() {
if(servletContext != null) {
return servletContext;
}
// Servlet 3.0+
// return super.getServletContext();
return null;
}
/**
* get session according to token
*
* @param token
* @param servletContext
* @return session associate to token or null if the token is invalid
*/
public HttpSession getSession(String token, ServletContext servletContext) {
checkConnection();
if (redisConnection.exists(RedisHttpSession.SESSION_PREFIX + token)) {
RedisHttpSession redisHttpSession = RedisHttpSession.createWithExistSession(token, servletContext, redisConnection);
return (HttpSession) new RedisHttpSessionProxy().bind(redisHttpSession);
} else {
throw new IllegalStateException("The HttpSession has already be invalidated.");
}
}
@Test
public void testInitJsfActionListener() throws NoSuchMethodException, SecurityException,
InvocationTargetException, IllegalAccessException {
final ServletContext servletContext = createNiceMock(ServletContext.class);
expect(servletContext.getInitParameter("com.sun.faces.enableTransitionTimeNoOpFlash"))
.andReturn(null).anyTimes();
final Enumeration<String> initParameterNames = Collections.emptyEnumeration();
expect(servletContext.getInitParameterNames()).andReturn(initParameterNames).anyTimes();
replay(servletContext);
final InitFacesContext facesContext = new InitFacesContext(servletContext);
final Method setter = FacesContext.class.getDeclaredMethod("setCurrentInstance",
FacesContext.class);
setter.setAccessible(true);
setter.invoke(null, facesContext);
FactoryFinder.setFactory(FactoryFinder.APPLICATION_FACTORY, AppFactory.class.getName());
verify(servletContext);
final ActionListener delegateActionListener = createNiceMock(ActionListener.class);
FacesContext.getCurrentInstance().getApplication()
.setActionListener(delegateActionListener);
JsfActionHelper.initJsfActionListener();
final UIComponent uiComponent = createNiceMock(UIComponent.class);
final ActionEvent actionEvent = new ActionEvent(uiComponent);
final ActionListener actionListener = FacesContext.getCurrentInstance().getApplication()
.getActionListener();
actionListener.processAction(actionEvent);
MonitoringProxy.getJsfCounter().setDisplayed(false);
actionListener.processAction(actionEvent);
MonitoringProxy.getJsfCounter().setDisplayed(true);
}
/**
* Constructor.
*
* @param servletContext the servlet context.
* @param id the id.
* @param newFlag the new flag.
*/
public HazelcastHttpSession(ServletContext servletContext, String id, boolean newFlag) {
this.servletContext = servletContext;
this.id = id;
this.newFlag = newFlag;
this.creationTime = System.currentTimeMillis();
this.lastAccessedTime = System.currentTimeMillis();
this.valid = true;
}
@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
throws Exception {
ServletContext servletContext = getServletContext();
Assert.state(servletContext != null, "No ServletContext");
RequestDispatcher rd = servletContext.getNamedDispatcher(this.servletName);
if (rd == null) {
throw new ServletException("No servlet with name '" + this.servletName + "' defined in web.xml");
}
// If already included, include again, else forward.
if (useInclude(request, response)) {
rd.include(request, response);
if (logger.isTraceEnabled()) {
logger.trace("Included servlet [" + this.servletName +
"] in ServletForwardingController '" + this.beanName + "'");
}
}
else {
rd.forward(request, response);
if (logger.isTraceEnabled()) {
logger.trace("Forwarded to servlet [" + this.servletName +
"] in ServletForwardingController '" + this.beanName + "'");
}
}
return null;
}
private SipURI getOutboundInterface(final ServletConfig config) {
final ServletContext context = config.getServletContext();
SipURI result = null;
@SuppressWarnings("unchecked")
final List<SipURI> uris = (List<SipURI>)context.getAttribute(OUTBOUND_INTERFACES);
for(final SipURI uri : uris) {
final String transport = uri.getTransportParam();
if("udp".equalsIgnoreCase(transport)) {
result = uri;
}
}
return result;
}
/**
* 从web的作用域中获取对象...
* @param key
* @param clazz
* @param <T>
* @return
*/
public static <T>T getObject(String key, Object obj, Class<T> clazz) {
AssertUtils.notNull(key,obj,clazz);
if (obj instanceof HttpServletRequest) {
HttpServletRequest request = (HttpServletRequest) obj;
return (T) request.getAttribute(key);
}else if(obj instanceof HttpSession){
HttpSession session = (HttpSession) obj;
return (T) session.getAttribute(key);
}else if(obj instanceof ServletContext){
ServletContext servletContext = (ServletContext) obj;
return (T) servletContext.getAttribute(key);
}
throw new IllegalArgumentException("obj must be {HttpServletRequest|HttpSession|ServletContext} ");
}
/** Creates a new instance of OptionsImpl */
public OptionsImpl(ServletContext context) {
ParserUtils.setSchemaResourcePrefix("/resources/schemas/");
ParserUtils.setDtdResourcePrefix("/resources/dtds/");
scanner = new TldScanner(context, false);
// #188703 - JSTL 1.1 handling
clearStaticHashSet(TldScanner.class, "systemUris");
clearStaticHashSet(TldScanner.class, "systemUrisJsf");
jspConfig = new JspConfig(context);
tagPluginManager = new TagPluginManager(context);
}
/**
* Destroyes the portlet container and removes it from servlet context.
*
* @param servletContext the servlet context.
*/
private void destroyContainer(ServletContext servletContext)
{
if (LOG.isInfoEnabled())
{
LOG.info("Shutting down Pluto Portal Driver...");
}
PortletContainer container = (PortletContainer)
servletContext.getAttribute(CONTAINER_KEY);
if (container != null)
{
try
{
container.destroy();
if (LOG.isInfoEnabled())
{
LOG.info("Pluto Portal Driver shut down.");
}
} catch (PortletContainerException ex)
{
LOG.error("Unable to shut down portlet container: "
+ ex.getMessage(), ex);
} finally
{
servletContext.removeAttribute(CONTAINER_KEY);
}
}
}
@Override
public void contextInitialized(ServletContextEvent event) {
/*
* This loader is not implemented using Spring's ServletContextInitializer
* because it does not provide websocket compliant ServerContainer.
*
* ServletContextEvent would expose javax.websocket.server.ServerContainer correctly.
*/
ServletContext context = event.getServletContext();
SimpleClassScanner scanner = SimpleClassScanner.getInstance();
Set<String> packages = scanner.getPackages(true);
Object sc = context.getAttribute("javax.websocket.server.ServerContainer");
if (sc instanceof ServerContainer) {
ServerContainer container = (ServerContainer) sc;
int total = 0;
for (String p : packages) {
List<Class<?>> endpoints = scanner.getAnnotatedClasses(p, ServerEndpoint.class);
for (Class<?> cls : endpoints) {
if (!Feature.isRequired(cls)) {
continue;
}
try {
container.addEndpoint(cls);
ServerEndpoint ep = cls.getAnnotation(ServerEndpoint.class);
total++;
log.info("{} registered as WEBSOCKET DISPATCHER {}", cls.getName(), Arrays.asList(ep.value()));
} catch (DeploymentException e) {
log.error("Unable to deploy websocket endpoint {} - {}", cls, e.getMessage());
}
}
}
if (total > 0) {
log.info("Total {} Websocket server endpoint{} registered (JSR-356)", total, total == 1 ? " is" : "s are");
}
} else {
log.error("Unable to register any ServerEndpoints because javax.websocket.server.ServerContainer is not available");
}
}
@Override
public void onStartup(ServletContext servletContext) throws ServletException
{
super.onStartup(servletContext);
ILoggerFactory loggerFactory = StaticLoggerBinder.getSingleton().getLoggerFactory();
if (loggerFactory instanceof LoggerContext)
{
LoggerContext loggerContext = (LoggerContext) loggerFactory;
loggerContext.setPackagingDataEnabled(false);
log.debug("Disabling logback packaging data");
}
}
public static void addSiteItemScriptVariables(Map<String, Object> variables, HttpServletRequest request,
HttpServletResponse response, ServletContext servletContext,
SiteItem item, Object templateModel) {
addCommonVariables(variables, request, response, servletContext);
addSecurityVariables(variables);
addContentModelVariable(variables, item);
addTemplateModelVariable(variables, templateModel);
}
@Test
public void servletContextAwareWithNullServletContextAndNonNullServletConfig() {
ServletContext servletContext = new MockServletContext();
ServletConfig servletConfig = new MockServletConfig(servletContext);
ServletContextAwareProcessor processor = new ServletContextAwareProcessor(null, servletConfig);
ServletContextAwareBean bean = new ServletContextAwareBean();
assertNull(bean.getServletContext());
processor.postProcessBeforeInitialization(bean, "testBean");
assertNotNull("ServletContext should have been set", bean.getServletContext());
assertEquals(servletContext, bean.getServletContext());
}
@Test
public void testGetAttribute() throws Exception {
ServletContext context = EasyMock.createNiceMock( ServletContext.class );
EasyMock.expect( context.getAttribute( "test-attribute-name" ) ).andReturn( "test-attribute-value" ).anyTimes();
EasyMock.replay( context );
UrlRewriteServletEnvironment env = new UrlRewriteServletEnvironment( context );
assertThat(env.getAttribute( "test-attribute-name" ), is( "test-attribute-value" ) );
}
/**
* lastUploaded
*/
private void lastUploaded(HttpServletRequest request, HttpServletResponse response) throws
PathNotFoundException, RepositoryException, IOException, ServletException, DatabaseException, OKMException {
log.debug("lastUploaded({}, {})", request, response);
ServletContext sc = getServletContext();
sc.setAttribute("action", WebUtils.getString(request, "action"));
sc.setAttribute("dashboardDocs", new com.openkm.servlet.frontend.DashboardServlet().getUserLastUploadedDocuments());
sc.getRequestDispatcher("/" + Config.MOBILE_CONTEXT + "/dashboard_browse.jsp").forward(request, response);
}
@Override
public void onStartup(Set<Class<?>> c, ServletContext ctx)
throws ServletException {
Servlet s = new TesterServlet();
ServletRegistration.Dynamic r = ctx.addServlet("TesterServlet1", s);
r.addMapping("/TesterServlet1");
}