Java Code Examples for javax.servlet.ServletContext

The following code examples are extracted from open source projects. You can click to vote up the examples that are useful to you.

Example 1

From project AceWiki, under directory /src/ch/uzh/ifi/attempto/acewiki/.

Source file: BackendServlet.java

  32 
vote

public void init(ServletConfig config) throws ServletException {
  Map<String,String> parameters=AceWikiServlet.getInitParameters(config);
  String name=config.getServletName();
  APE.setParameters(parameters);
  backend=new Backend(parameters);
  ServletContext ctx=config.getServletContext();
  ctx.setAttribute(name,backend);
  super.init(config);
}
 

Example 2

From project agileBase, under directory /gtpb_server/src/com/gtwm/pb/servlets/.

Source file: CalendarPublisher.java

  32 
vote

public void init() throws ServletException {
  ServletContext servletContext=getServletContext();
  this.databaseDefn=(DatabaseInfo)servletContext.getAttribute("com.gtwm.pb.servlets.databaseDefn");
  if (this.databaseDefn == null) {
    throw new ServletException("Error starting CalendarPublisher servlet. No databaseDefn object in the servlet context");
  }
}
 

Example 3

From project ALP, under directory /workspace/alp-reporter-fe/src/main/java/com/lohika/alp/reporter/fe/controller/.

Source file: LogController.java

  32 
vote

@RequestMapping(method=RequestMethod.GET,value="/results/test-method/{testMethodId}/log/") String getLog(Model model,HttpServletRequest request,@PathVariable("testMethodId") long id) throws IOException {
  ServletContext sc=request.getSession().getServletContext();
  String datalogsPath=sc.getInitParameter("datalogsPath");
  InputStream is=logStorage.getLog(id,"index.xml",datalogsPath);
  model.addAttribute(is);
  model.addAttribute("backButtonUrl",request.getHeader("referer"));
  model.addAttribute("contextPath","../../../..");
  return "log";
}
 

Example 4

From project autopatch, under directory /src/main/java/com/tacitknowledge/util/migration/jdbc/util/.

Source file: ConfigurationUtil.java

  32 
vote

/** 
 * Returns the value of the specified servlet context initialization parameter.
 * @param param          the parameter to return
 * @param sce            the <code>ServletContextEvent</code> being handled
 * @param caller         calling object, used for printing information if there is a problem
 * @param throwException if <code>true</code> then the method will throw an exception; if<code>false</code> is supplied then it will return <code>null</code>
 * @return the value of the specified servlet context initialization parameter if found;<code>null</code> otherwise
 * @throws IllegalArgumentException if the parameter does not exist
 */
private static String getServletContextParam(String param,ServletContextEvent sce,Object caller,boolean throwException) throws IllegalArgumentException {
  ServletContext context=sce.getServletContext();
  String value=context.getInitParameter(param);
  if (value == null && throwException) {
    throw new IllegalArgumentException("'" + param + "' is a required "+ "servlet context initialization parameter for the \""+ caller.getClass().getName()+ "\" class.  Aborting.");
  }
  return value;
}
 

Example 5

From project b3log-latke, under directory /latke/src/main/java/org/b3log/latke/servlet/.

Source file: AbstractServletListener.java

  32 
vote

/** 
 * Initializes context,  {@linkplain #webRoot web root}, locale and runtime environment.
 * @param servletContextEvent servlet context event
 */
@Override public void contextInitialized(final ServletContextEvent servletContextEvent){
  Latkes.initRuntimeEnv();
  LOGGER.info("Initializing the context....");
  Latkes.setLocale(Locale.SIMPLIFIED_CHINESE);
  LOGGER.log(Level.INFO,"Default locale[{0}]",Latkes.getLocale());
  final ServletContext servletContext=servletContextEvent.getServletContext();
  webRoot=servletContext.getRealPath("") + File.separator;
  LOGGER.log(Level.INFO,"Server[webRoot={0}, contextPath={1}]",new Object[]{webRoot,servletContextEvent.getServletContext().getContextPath()});
  CronService.start();
}
 

Example 6

From project CalendarPortlet, under directory /src/main/java/org/jasig/portlet/calendar/spring/.

Source file: PortletApplicationContextLocator.java

  32 
vote

/** 
 * @return The WebApplicationContext for the portal
 * @throws IllegalStateException if no ServletContext is available to retrieve a WebApplicationContext for or if the root WebApplicationContext could not be found
 * @deprecated This method is a work-around for areas in uPortal that do not have the ability to use the {@link WebApplicationContextUtils#getRequiredWebApplicationContext(ServletContext)} directly.
 */
@Deprecated public static WebApplicationContext getRequiredWebApplicationContext(){
  final ServletContext context=servletContext;
  if (context == null) {
    throw new IllegalStateException("No ServletContext is available to load a WebApplicationContext for. Is this ServletContextListener not configured or has the ServletContext been destroyed?");
  }
  return WebApplicationContextUtils.getRequiredWebApplicationContext(context);
}
 

Example 7

From project candlepin, under directory /src/main/java/org/candlepin/guice/.

Source file: CandlepinContextListener.java

  32 
vote

@Override public void contextInitialized(final ServletContextEvent event){
  super.contextInitialized(event);
  final ServletContext context=event.getServletContext();
  final Registry registry=(Registry)context.getAttribute(Registry.class.getName());
  final ResteasyProviderFactory providerFactory=(ResteasyProviderFactory)context.getAttribute(ResteasyProviderFactory.class.getName());
  injector=Guice.createInjector(getModules());
  processInjector(registry,providerFactory,injector);
  hornetqListener=injector.getInstance(HornetqContextListener.class);
  hornetqListener.contextInitialized(injector);
  pinsetterListener=injector.getInstance(PinsetterContextListener.class);
  pinsetterListener.contextInitialized();
}
 

Example 8

From project cas, under directory /cas-server-core/src/main/java/org/jasig/cas/web/init/.

Source file: SafeContextLoaderListener.java

  32 
vote

public void contextInitialized(final ServletContextEvent sce){
  try {
    this.delegate.contextInitialized(sce);
  }
 catch (  Throwable t) {
    final String message="SafeContextLoaderListener: \n" + "The Spring ContextLoaderListener we wrap threw on contextInitialized.\n" + "But for our having caught this error, the web application context would not have initialized.";
    log.error(message,t);
    System.err.println(message);
    t.printStackTrace();
    ServletContext context=sce.getServletContext();
    context.log(message,t);
    context.setAttribute(CAUGHT_THROWABLE_KEY,t);
  }
}
 

Example 9

From project Coffee-Framework, under directory /coffeeframework-core/src/main/java/coffee/servlet/.

Source file: CoffeeUnitializer.java

  32 
vote

@Override public void contextDestroyed(ServletContextEvent sce){
  ServletContext servletContext=sce.getServletContext();
  servletContext.log("[Coffee] Removing Coffee Caches...");
  CoffeeApplicationContext applicationContext=Cafeteria.getOrCreateApplicationContext(servletContext);
  applicationContext.clearCache();
  CoffeeBinder.clearCache();
  CoffeeLifeCycle.clearCache();
  Cafeteria.destroyApplicationContext(applicationContext);
  System.gc();
  servletContext.log("[Coffee] Released memory will be available next time Garbage Collection back to the scene.");
}
 

Example 10

From project cometd, under directory /cometd-java/cometd-java-oort/src/test/java/org/cometd/oort/.

Source file: OortDemoServlet.java

  32 
vote

public void init(ServletConfig config) throws ServletException {
  _config=config;
  ServletContext context=config.getServletContext();
  BayeuxServer bayeux=(BayeuxServer)context.getAttribute(BayeuxServer.ATTRIBUTE);
  Oort oort=(Oort)context.getAttribute(Oort.OORT_ATTRIBUTE);
  Seti seti=(Seti)context.getAttribute(Seti.SETI_ATTRIBUTE);
  _processor=new ServerAnnotationProcessor(bayeux,oort,seti);
  _service=new OortChatService();
  _processor.process(_service);
  bayeux.addExtension(new TimesyncExtension());
}
 

Example 11

From project commons-j, under directory /src/main/java/nerds/antelax/commons/net/pubsub/.

Source file: PubSubServerContextListener.java

  32 
vote

@Override public synchronized void contextInitialized(final ServletContextEvent ctx){
  final ServletContext sc=ctx.getServletContext();
  final Collection<InetSocketAddress> cluster=sc != null ? NetUtil.hostPortPairsFromString(sc.getInitParameter(CLUSTER_INIT_PARAM),PubSubServer.DEFAULT_ADDRESS.getPort()) : EMPTY;
  REMOTE_SERVERS.set(Collections2.filter(cluster,Predicates.not(NetUtil.machineLocalSocketAddress())));
  if (Iterables.any(cluster,NetUtil.machineLocalSocketAddress())) {
    server=new PubSubServer(cluster);
    ctx.getServletContext().log("Starting PubSub server, this machine is part of the cluster definition[" + cluster + "]");
    server.start();
  }
 else {
    server=null;
    ctx.getServletContext().log("No PubSub server started, remotes available for final clients are " + remoteServers());
  }
}
 

Example 12

From project crash, under directory /shell/core/src/main/java/org/crsh/plugin/.

Source file: WebPluginLifeCycle.java

  32 
vote

public void contextDestroyed(ServletContextEvent sce){
  if (registered) {
    ServletContext sc=sce.getServletContext();
    String contextPath=sc.getContextPath();
synchronized (lock) {
      contextMap.remove(contextPath);
      registered=false;
      stop();
    }
  }
}
 

Example 13

From project entando-core-engine, under directory /src/main/java/com/agiletec/aps/servlet/.

Source file: StartupListener.java

  32 
vote

/** 
 * @see javax.servlet.ServletContextListener#contextInitialized(javax.servlet.ServletContextEvent)
 */
public void contextInitialized(ServletContextEvent event){
  ServletContext svCtx=event.getServletContext();
  String msg=this.getClass().getName() + ": INIT " + svCtx.getServletContextName();
  System.out.println(msg);
  super.contextInitialized(event);
  msg=this.getClass().getName() + ": INIT DONE " + svCtx.getServletContextName();
  System.out.println(msg);
}
 

Example 14

From project Extlet6, under directory /liferay-6.0.5-patch/portal-impl/src/com/liferay/portal/servlet/.

Source file: MainServlet.java

  32 
vote

protected void checkPortletRequestProcessor(HttpServletRequest request) throws ServletException {
  ServletContext servletContext=getServletContext();
  PortletRequestProcessor portletReqProcessor=(PortletRequestProcessor)servletContext.getAttribute(WebKeys.PORTLET_STRUTS_PROCESSOR);
  if (portletReqProcessor == null) {
    ModuleConfig moduleConfig=getModuleConfig(request);
    portletReqProcessor=PortletRequestProcessor.getInstance(this,moduleConfig);
    servletContext.setAttribute(WebKeys.PORTLET_STRUTS_PROCESSOR,portletReqProcessor);
  }
}
 

Example 15

From project 3Dto2DApplet, under directory /src/java/nl/dannyarends/www/http/.

Source file: Webserver.java

  31 
vote

public void forward(ServletRequest _request,ServletResponse _response) throws ServletException, java.io.IOException {
  _request.removeAttribute("javax.servlet.forward.request_uri");
  _response.reset();
  servlet.service(new HttpServletRequestWrapper((HttpServletRequest)_request){
    public java.lang.String getPathInfo(){
      return dispatchLen >= dispatchPath.length() ? null : dispatchPath.substring(dispatchLen);
    }
    public String getRequestURI(){
      return dispatchPath;
    }
    public String getQueryString(){
      return dispatchQuery;
    }
    public String getPathTranslated(){
      ServletContext context=((HttpServletRequest)getRequest()).getSession().getServletContext();
      return context.getRealPath(((HttpServletRequest)getRequest()).getContextPath());
    }
    public String getServletPath(){
      return dispatchLen <= 0 ? "" : dispatchPath.substring(0,dispatchLen);
    }
    public synchronized Enumeration<?> getAttributeNames(){
      if (super.getAttribute("javax.servlet.forward.request_uri") == null) {
        setAttribute("javax.servlet.forward.request_uri",super.getRequestURI());
        setAttribute("javax.servlet.forward.context_path",this.getContextPath());
        setAttribute("javax.servlet.forward.servlet_path",super.getServletPath());
        setAttribute("javax.servlet.forward.path_info",super.getPathInfo());
        setAttribute("javax.servlet.forward.query_string",super.getQueryString());
      }
      return super.getAttributeNames();
    }
    public Object getAttribute(    String name){
      getAttributeNames();
      return super.getAttribute(name);
    }
  }
,_response);
}
 

Example 16

From project alphaportal_dev, under directory /sys-src/alphaportal/web/src/main/java/alpha/portal/webapp/listener/.

Source file: StartupListener.java

  31 
vote

/** 
 * {@inheritDoc}
 */
@SuppressWarnings("unchecked") public void contextInitialized(final ServletContextEvent event){
  StartupListener.log.debug("Initializing context...");
  final ServletContext context=event.getServletContext();
  Map<String,Object> config=(HashMap<String,Object>)context.getAttribute(Constants.CONFIG);
  if (config == null) {
    config=new HashMap<String,Object>();
  }
  if (context.getInitParameter(Constants.CSS_THEME) != null) {
    config.put(Constants.CSS_THEME,context.getInitParameter(Constants.CSS_THEME));
  }
  final ApplicationContext ctx=WebApplicationContextUtils.getRequiredWebApplicationContext(context);
  PasswordEncoder passwordEncoder=null;
  try {
    final ProviderManager provider=(ProviderManager)ctx.getBean("org.springframework.security.authentication.ProviderManager#0");
    for (    final Object o : provider.getProviders()) {
      final AuthenticationProvider p=(AuthenticationProvider)o;
      if (p instanceof RememberMeAuthenticationProvider) {
        config.put("rememberMeEnabled",Boolean.TRUE);
      }
 else       if (ctx.getBean("passwordEncoder") != null) {
        passwordEncoder=(PasswordEncoder)ctx.getBean("passwordEncoder");
      }
    }
  }
 catch (  final NoSuchBeanDefinitionException n) {
    StartupListener.log.debug("authenticationManager bean not found, assuming test and ignoring...");
  }
  context.setAttribute(Constants.CONFIG,config);
  if (StartupListener.log.isDebugEnabled()) {
    StartupListener.log.debug("Remember Me Enabled? " + config.get("rememberMeEnabled"));
    if (passwordEncoder != null) {
      StartupListener.log.debug("Password Encoder: " + passwordEncoder.getClass().getSimpleName());
    }
    StartupListener.log.debug("Populating drop-downs...");
  }
  StartupListener.setupContext(context);
}
 

Example 17

From project aranea, under directory /server/src/main/java/no/dusken/aranea/filter/.

Source file: PluginAwareUrlRewriteFilter.java

  31 
vote

@Override protected void loadUrlRewriter(FilterConfig filterConfig) throws ServletException {
  ServletContext context=filterConfig.getServletContext();
  InputStream inputStream=context.getResourceAsStream(DEFAULT_WEB_CONF_PATH);
  URL confUrl=null;
  try {
    confUrl=context.getResource(DEFAULT_WEB_CONF_PATH);
  }
 catch (  MalformedURLException e) {
    log.debug("Malformed url",e);
  }
  String confUrlStr=null;
  if (confUrl != null) {
    confUrlStr=confUrl.toString();
  }
  if (inputStream == null) {
    log.error("unable to find urlrewrite conf file at " + DEFAULT_WEB_CONF_PATH);
  }
 else {
    Conf conf=new PluginAwareConf(context,inputStream,DEFAULT_WEB_CONF_PATH,confUrlStr);
    checkConf(conf);
  }
}
 

Example 18

From project arquillian-container-tomcat, under directory /tomcat-embedded-6/src/main/java/org/jboss/arquillian/container/tomcat/embedded_6/.

Source file: EmbeddedContextConfig.java

  31 
vote

/** 
 * Process the META-INF/context.xml descriptor in the web application root. This descriptor is not processed when a webapp is added programmatically through a StandardContext
 */
protected void applicationContextConfig(){
  ServletContext servletContext=context.getServletContext();
  InputStream stream=servletContext.getResourceAsStream("/" + Constants.ApplicationContextXml);
  if (stream == null) {
    return;
  }
synchronized (contextDigester) {
    URL url=null;
    try {
      url=servletContext.getResource("/" + Constants.ApplicationContextXml);
    }
 catch (    MalformedURLException e) {
      throw new AssertionError("/" + Constants.ApplicationContextXml + " should not be considered a malformed URL");
    }
    InputSource is=new InputSource(url.toExternalForm());
    is.setByteStream(stream);
    contextDigester.push(context);
    try {
      contextDigester.parse(is);
    }
 catch (    Exception e) {
      ok=false;
      log.error("Parse error in context.xml for " + context.getName(),e);
    }
 finally {
      contextDigester.reset();
      try {
        if (stream != null) {
          stream.close();
        }
      }
 catch (      IOException e) {
        log.error("Error closing context.xml for " + context.getName(),e);
      }
    }
  }
  log.debug("Done processing " + Constants.ApplicationContextXml + " descriptor");
}
 

Example 19

From project arquillian_deprecated, under directory /containers/tomcat-embedded-6/src/main/java/org/jboss/arquillian/container/tomcat/embedded_6/.

Source file: EmbeddedContextConfig.java

  31 
vote

/** 
 * Process the META-INF/context.xml descriptor in the web application root. This descriptor is not processed when a webapp is added programmatically through a StandardContext
 */
protected void applicationContextConfig(){
  ServletContext servletContext=context.getServletContext();
  InputStream stream=servletContext.getResourceAsStream("/" + Constants.ApplicationContextXml);
  if (stream == null) {
    return;
  }
synchronized (contextDigester) {
    URL url=null;
    try {
      url=servletContext.getResource("/" + Constants.ApplicationContextXml);
    }
 catch (    MalformedURLException e) {
      throw new AssertionError("/" + Constants.ApplicationContextXml + " should not be considered a malformed URL");
    }
    InputSource is=new InputSource(url.toExternalForm());
    is.setByteStream(stream);
    contextDigester.push(context);
    try {
      contextDigester.parse(is);
    }
 catch (    Exception e) {
      ok=false;
      log.error("Parse error in context.xml for " + context.getName(),e);
    }
 finally {
      contextDigester.reset();
      try {
        if (stream != null) {
          stream.close();
        }
      }
 catch (      IOException e) {
        log.error("Error closing context.xml for " + context.getName(),e);
      }
    }
  }
  log.debug("Done processing " + Constants.ApplicationContextXml + " descriptor");
}
 

Example 20

From project Blitz, under directory /src/com/laxser/blitz/web/impl/module/.

Source file: ModuleAppContext.java

  31 
vote

public static ModuleAppContext createModuleContext(WebApplicationContext parent,List<URL> contextResources,String[] messageBasenames,String uniqueId,String namespace) throws IOException {
  long startTime=System.currentTimeMillis();
  String loadingMsg="[moduleContext.create] Loading Spring '" + namespace + "' WebApplicationContext";
  logger.info(loadingMsg);
  Assert.notNull(parent);
  ServletContext servletContext=parent.getServletContext();
  Assert.notNull(servletContext);
  ModuleAppContext wac=new ModuleAppContext();
  wac.setParent(parent);
  wac.setServletContext(servletContext);
  wac.setContextResources(toResources(contextResources));
  wac.setId(uniqueId);
  wac.setNamespace(namespace);
  wac.setMessageBaseNames(messageBasenames);
  wac.refresh();
  if (logger.isDebugEnabled()) {
    long elapsedTime=System.currentTimeMillis() - startTime;
    logger.debug("[moduleContext.create] Using context class [" + wac.getClass().getName() + "] for "+ namespace+ " WebApplicationContext");
    logger.info("[moduleContext.create] " + namespace + " WebApplicationContext: initialization completed in "+ elapsedTime+ " ms");
  }
  return wac;
}
 

Example 21

From project brix-cms, under directory /brix-rmiserver/src/main/java/org/brixcms/rmiserver/web/dav/.

Source file: WebDavServlet.java

  31 
vote

@Override public void init(ServletConfig config) throws ServletException {
  super.init(config);
  final ServletContext sc=config.getServletContext();
  ApplicationContext context=WebApplicationContextUtils.getWebApplicationContext(sc);
  if (context == null) {
    throw new IllegalStateException("Could not find application context");
  }
  repository=(Repository)BeanFactoryUtils.beanOfTypeIncludingAncestors(context,Repository.class);
  if (repository == null) {
    throw new IllegalStateException("Could not find JackRabbit repository in spring context");
  }
  UserService users=(UserService)BeanFactoryUtils.beanOfTypeIncludingAncestors(context,UserService.class);
  if (repository == null) {
    throw new IllegalStateException("Could not find UserService implementation in spring context");
  }
  authorizer=new Authorizer(users);
  credentialsProvider=getCredentialsProvider();
}
 

Example 22

From project conversation, under directory /owb/src/test/java/org/jboss/seam/conversation/support/.

Source file: HackContextLifecycleListener.java

  31 
vote

public void lifecycleEvent(LifecycleEvent event){
  try {
    if (event.getSource() instanceof StandardContext) {
      StandardContext context=(StandardContext)event.getSource();
      if (event.getType().equals(Lifecycle.AFTER_START_EVENT)) {
        ServletContext scontext=context.getServletContext();
        URL url=scontext.getResource("/WEB-INF/beans.xml");
        if (url != null) {
          System.setProperty("org.apache.webbeans.application.jsp","false");
          String[] oldListeners=context.findApplicationListeners();
          LinkedList<String> listeners=new LinkedList<String>();
          listeners.addFirst(WebBeansConfigurationListener.class.getName());
          for (          String listener : oldListeners) {
            listeners.add(listener);
            context.removeApplicationListener(listener);
          }
          for (          String listener : listeners) {
            context.addApplicationListener(listener);
          }
          context.addApplicationListener(TomcatSecurityListener.class.getName());
          processor=context.getAnnotationProcessor();
          AnnotationProcessor custom=new TomcatAnnotProcessor(context.getLoader().getClassLoader(),processor);
          context.setAnnotationProcessor(custom);
          context.getServletContext().setAttribute(AnnotationProcessor.class.getName(),custom);
        }
      }
 else       if (event.getType().equals(Lifecycle.AFTER_STOP_EVENT)) {
        context.setAnnotationProcessor(processor);
      }
    }
 else {
      super.lifecycleEvent(event);
    }
  }
 catch (  Exception e) {
    e.printStackTrace();
  }
}
 

Example 23

From project core_1, under directory /deploy/webapp/src/main/java/org/switchyard/deployment/.

Source file: WebApplicationDeployer.java

  31 
vote

@Override public void contextInitialized(ServletContextEvent sce){
  ServletContext servletContext=sce.getServletContext();
  InputStream switchYardConfig=servletContext.getResourceAsStream("WEB-INF/classes/" + AbstractDeployment.SWITCHYARD_XML);
  if (switchYardConfig != null) {
    try {
      _switchyard=new SwitchYard(switchYardConfig);
      _switchyard.start();
    }
 catch (    IOException e) {
      _logger.debug("Error deploying SwitchYard within Web Application '" + servletContext.getServletContextName() + "'.  SwitchYard not deployed.",e);
    }
  }
 else {
    _logger.debug("No SwitchYard configuration found at '" + AbstractDeployment.SWITCHYARD_XML + "' in Web Application '"+ servletContext.getServletContextName()+ "'.  SwitchYard not deployed.");
  }
}
 

Example 24

From project empire-db, under directory /empire-db-jsf2/src/main/java/org/apache/empire/jsf2/app/.

Source file: AppStartupListener.java

  31 
vote

@Override public void processEvent(SystemEvent event) throws AbortProcessingException {
  log.info("ApplicationStartupListener:processEvent");
  if (event instanceof PostConstructApplicationEvent) {
    Application app=((PostConstructApplicationEvent)event).getApplication();
    if (!(app instanceof FacesApplication))     throw new AbortProcessingException("Error: Application is not a " + FacesApplication.class.getName() + " instance. Please create a ApplicationFactory!");
    ServletContext servletContext=(ServletContext)FacesContext.getCurrentInstance().getExternalContext().getContext();
    FacesApplication jsfApp=(FacesApplication)app;
    jsfApp.init(servletContext);
    if (servletContext.getAttribute(FacesApplication.APPLICATION_ATTRIBUTE) != null) {
      log.warn("WARNING: Ambiguous application definition. An object of name '{}' already exists on application scope!",FacesApplication.APPLICATION_ATTRIBUTE);
    }
    servletContext.setAttribute(FacesApplication.APPLICATION_ATTRIBUTE,jsfApp);
    jsfApp.initComplete(servletContext);
  }
 else   if (event instanceof PreDestroyApplicationEvent) {
    log.info("Processing PreDestroyApplicationEvent");
  }
}
 

Example 25

From project ajah, under directory /ajah-spring-mvc/src/main/java/com/ajah/spring/mvc/util/.

Source file: FilterUtils.java

  29 
vote

/** 
 * Convenience method for adding a filter that is available as a Spring bean/service to all requests.
 * @see ServletContext#addFilter(String,Class)
 * @param filterClass The class of Filter to instantiate.
 * @param appContext The application context to find the bean in.
 * @param servletContext
 * @return The Dynamic Mapping created by this method.
 */
public static Dynamic add(final Class<? extends Filter> filterClass,final ApplicationContext appContext,final ServletContext servletContext){
  final Filter filter=appContext.getBean(filterClass);
  final FilterRegistration.Dynamic reg=servletContext.addFilter(filterClass.getName(),filter);
  reg.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST),true,"/*");
  return reg;
}
 

Example 26

From project amber, under directory /oauth-2.0/resourceserver-filter/src/main/java/org/apache/amber/oauth2/rsfilter/.

Source file: OAuthUtils.java

  29 
vote

public static <T>T initiateServletContext(ServletContext context,String key,Class<T> expectedClass) throws ServletException {
  T provider=(T)context.getAttribute(key);
  if (provider != null) {
    return provider;
  }
  provider=(T)loadObject(context,key,expectedClass);
  context.setAttribute(key,provider);
  return provider;
}
 

Example 27

From project arquillian-extension-spring, under directory /arquillian-service-integration-spring-3-int-tests/src/test/java/org/jboss/arquillian/spring/testsuite/beans/web/.

Source file: EmployeeWebInitializer.java

  29 
vote

/** 
 * {@inheritDoc}
 */
public void onStartup(ServletContext servletContext) throws ServletException {
  AnnotationConfigWebApplicationContext webContext=new AnnotationConfigWebApplicationContext();
  webContext.register(WebAppConfig.class);
  servletContext.addListener(new ContextLoaderListener(new AnnotationConfigWebApplicationContext()));
  ServletRegistration.Dynamic servletConfig=servletContext.addServlet("employee",new DispatcherServlet(webContext));
  servletConfig.setLoadOnStartup(1);
  servletConfig.addMapping("*.htm");
}
 

Example 28

From project capedwarf-blue, under directory /tasks/src/main/java/org/jboss/capedwarf/tasks/.

Source file: TasksServletRequestCreator.java

  29 
vote

public HttpServletRequest createServletRequest(ServletContext context,Message message) throws Exception {
  final AbstractHttpServletRequest request;
  if (message instanceof BytesMessage) {
    request=new BytesServletRequest(context,(BytesMessage)message);
  }
 else {
    request=new TasksServletRequest(context);
  }
  final Map<String,Set<String>> headers=get(message,HEADERS);
  request.addHeaders(headers);
  final Map<String,Set<String>> params=get(message,PARAMS);
  request.addParameters(params);
  return request;
}
 

Example 29

From project capedwarf-green, under directory /server-api/src/main/java/org/jboss/capedwarf/server/api/mvc/impl/.

Source file: BasicPath2Controller.java

  29 
vote

@SuppressWarnings({"unchecked"}) protected void doInitialize(ServletContext context){
  InjectionTarget it=manager.createInjectionTarget(manager.createAnnotatedType(getHandlerClass()));
  CreationalContext cc=manager.createCreationalContext(null);
  handler=(RequestHandler)it.produce(cc);
  it.inject(handler,cc);
  handler.initialize(context);
}
 

Example 30

From project caseconductor-platform, under directory /utest-portal-webapp/src/main/java/com/utest/portal/log/.

Source file: RepositorySelector.java

  29 
vote

public static synchronized void init(final ServletContext servletContext) throws ServletException {
  if (!initialized) {
    defaultRepository=LogManager.getLoggerRepository();
    final RepositorySelector theSelector=new RepositorySelector();
    LogManager.setRepositorySelector(theSelector,guard);
    initialized=true;
  }
  final Hierarchy hierarchy=new Hierarchy(new RootLogger(Level.DEBUG));
  loadLog4JConfig(servletContext,hierarchy);
  final ClassLoader loader=Thread.currentThread().getContextClassLoader();
  repositories.put(loader,hierarchy);
}
 

Example 31

From project chukwa, under directory /src/main/java/org/apache/hadoop/chukwa/datacollection/agent/rest/.

Source file: AdaptorController.java

  29 
vote

/** 
 * Adds an adaptor to the agent and returns the adaptor info.
 * @param context servletContext
 * @param viewType type of view to return (text|xml)
 * @param postBody JSON post body
 * @return Response object
 */
@POST @Consumes("application/json") @Produces({"text/xml","text/plain"}) public Response addAdaptor(@Context ServletContext context,@QueryParam("viewType") String viewType,String postBody){
  ChukwaAgent agent=(ChukwaAgent)context.getAttribute("ChukwaAgent");
  if (postBody == null)   return badRequestResponse("Empty POST body.");
  StringBuilder addCommand=new StringBuilder("add ");
  try {
    JSONObject reqJson=new JSONObject(postBody);
    String dataType=reqJson.getString("DataType");
    String adaptorClass=reqJson.getString("AdaptorClass");
    String adaptorParams=fetchOptionalString(reqJson,"AdaptorParams");
    long offset=fetchOptionalLong(reqJson,"Offset",0);
    addCommand.append(adaptorClass).append(' ');
    addCommand.append(dataType);
    if (adaptorParams != null)     addCommand.append(' ').append(adaptorParams);
    addCommand.append(' ').append(offset);
  }
 catch (  JSONException e) {
    return badRequestResponse("Invalid JSON passed: '" + postBody + "', error: "+ e.getMessage());
  }
  try {
    String adaptorId=agent.processAddCommandE(addCommand.toString());
    return doGetAdaptor(agent,adaptorId,viewType);
  }
 catch (  AdaptorException e) {
    return badRequestResponse("Could not add adaptor for postBody: '" + postBody + "', error: "+ e.getMessage());
  }
}
 

Example 32

From project core_4, under directory /impl/src/main/java/org/richfaces/application/push/impl/.

Source file: PushContextFactoryImpl.java

  29 
vote

private static String getApplicationContextName(FacesContext facesContext){
  Object contextObject=facesContext.getExternalContext().getContext();
  if (contextObject instanceof ServletContext) {
    return ((ServletContext)contextObject).getContextPath();
  }
  return "/";
}
 

Example 33

From project core_5, under directory /exo.core.component.security.core/src/main/java/org/exoplatform/services/security/web/.

Source file: ConversationStateListener.java

  29 
vote

/** 
 * @param sctx {@link ServletContext}
 * @return actual ExoContainer instance
 */
protected ExoContainer getContainerIfPresent(ServletContext sctx){
  ExoContainer container=ExoContainerContext.getCurrentContainerIfPresent();
  if (container instanceof RootContainer) {
    container=PortalContainer.getCurrentInstance(sctx);
    if (container == null) {
      container=ExoContainerContext.getTopContainer();
    }
  }
  return container;
}
 

Example 34

From project doorkeeper, under directory /core/src/main/java/net/dataforte/doorkeeper/.

Source file: Doorkeeper.java

  29 
vote

/** 
 * @param sc
 * @return
 */
public synchronized static Doorkeeper getInstance(ServletContext sc){
  Doorkeeper instance=(Doorkeeper)sc.getAttribute(Doorkeeper.class.getName());
  if (instance == null) {
    instance=new Doorkeeper(sc);
    sc.setAttribute(Doorkeeper.class.getName(),instance);
  }
  return instance;
}