javax.servlet.ServletContext Java Examples
The following examples show how to use
javax.servlet.ServletContext.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: IWAUIAuthenticator.java From carbon-identity with Apache License 2.0 | 7 votes |
/** * {@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); }
Example #2
Source File: UtilHttp.java From scipio-erp with Apache License 2.0 | 6 votes |
/** * 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; }
Example #3
Source File: TestPluginMonitoringFilter.java From javamelody with Apache License 2.0 | 6 votes |
@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); }
Example #4
Source File: WebConfigurer.java From flowable-engine with Apache License 2.0 | 6 votes |
/** * 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; }
Example #5
Source File: UrlRewriteResponseTest.java From knox with Apache License 2.0 | 6 votes |
@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" ) ); }
Example #6
Source File: SpringWebInitializer.java From Spring-5.0-Cookbook with MIT License | 6 votes |
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, "/*"); }
Example #7
Source File: JSR356WebsocketInitializer.java From flow with Apache License 2.0 | 6 votes |
@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(); } } } }
Example #8
Source File: InterfaceX_ServiceSideServer.java From yawl with GNU Lesser General Public License v3.0 | 6 votes |
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(); } }
Example #9
Source File: ServletDeployer.java From flow with Apache License 2.0 | 6 votes |
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())); } }
Example #10
Source File: PluginContextListener.java From activemq-artemis with Apache License 2.0 | 6 votes |
@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()); }
Example #11
Source File: TestStandardContext.java From Tomcat8-Source-Read with MIT License | 6 votes |
@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); }
Example #12
Source File: PrometheusServlet.java From dropwizard-prometheus with Apache License 2.0 | 6 votes |
@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); }
Example #13
Source File: AbstractMgwtManifestServletTest.java From gwt-appcache with Apache License 2.0 | 5 votes |
@Override public ServletContext getServletContext() { if ( null == _servletContext ) { _servletContext = mock( ServletContext.class ); } return _servletContext; }
Example #14
Source File: ProvisioningServiceBean.java From development with Apache License 2.0 | 5 votes |
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; }
Example #15
Source File: SessionRepositoryFilter.java From lemon with Apache License 2.0 | 5 votes |
public ServletContext getServletContext() { if(servletContext != null) { return servletContext; } // Servlet 3.0+ // return super.getServletContext(); return null; }
Example #16
Source File: RedisHttpSessionRepository.java From RedisHttpSession with Apache License 2.0 | 5 votes |
/** * 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."); } }
Example #17
Source File: TestJsf.java From javamelody with Apache License 2.0 | 5 votes |
@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); }
Example #18
Source File: HazelcastHttpSession.java From piranha with BSD 3-Clause "New" or "Revised" License | 5 votes |
/** * 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; }
Example #19
Source File: ServletForwardingController.java From spring-analysis-note with MIT License | 5 votes |
@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; }
Example #20
Source File: PresenceManager.java From JVoiceXML with GNU Lesser General Public License v2.1 | 5 votes |
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; }
Example #21
Source File: WebUtils.java From opencron with Apache License 2.0 | 5 votes |
/** * 从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} "); }
Example #22
Source File: OptionsImpl.java From netbeans with Apache License 2.0 | 5 votes |
/** 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); }
Example #23
Source File: PortalStartupListener.java From portals-pluto with Apache License 2.0 | 5 votes |
/** * 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); } } }
Example #24
Source File: WsLoader.java From mercury with Apache License 2.0 | 5 votes |
@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"); } }
Example #25
Source File: SpringBootWebApplication.java From runelite with BSD 2-Clause "Simplified" License | 5 votes |
@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"); } }
Example #26
Source File: GroovyScriptUtils.java From engine with GNU General Public License v3.0 | 5 votes |
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); }
Example #27
Source File: ServletContextAwareProcessorTests.java From java-technology-stack with MIT License | 5 votes |
@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()); }
Example #28
Source File: UrlRewriteServletEnvironmentTest.java From knox with Apache License 2.0 | 5 votes |
@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" ) ); }
Example #29
Source File: DashboardServlet.java From document-management-system with GNU General Public License v2.0 | 5 votes |
/** * 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); }
Example #30
Source File: TesterServletContainerInitializer1.java From Tomcat7.0.67 with Apache License 2.0 | 5 votes |
@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"); }