@Override
  public void configure(AtmosphereConfig config) {
    try {

      String s = config.getInitParameter(ATMOSPHERE_SPRING_EXCLUDE_CLASSES);
      if (s != null) {
        String[] list = s.split(",");
        for (String clazz : list) {
          excludedFromInjection.add(IOUtils.loadClass(getClass(), clazz));
        }

        if (list.length > 0) {
          preventSpringInjection = true;
        }
      }

      context = new AnnotationConfigApplicationContext();
      context.setParent(
          WebApplicationContextUtils.getWebApplicationContext(
              config.framework().getServletContext()));

      context.refresh();

      // Hack to make it injectable
      context.register(AtmosphereConfig.class);
      ((AtmosphereConfig)
              context.getBean(AtmosphereConfig.class.getCanonicalName(), config.framework()))
          .populate(config);
    } catch (Exception ex) {
      logger.warn("Unable to configure injection", ex);
    }
  }
  /**
   * Get the application bean in Spring's context.
   *
   * @see AbstractApplicationServlet#getNewApplication(HttpServletRequest)
   */
  @Override
  protected Application getNewApplication(HttpServletRequest request) throws ServletException {

    WebApplicationContext wac =
        WebApplicationContextUtils.getWebApplicationContext(getServletContext());

    if (wac == null) {
      throw new ServletException(
          "Cannot get an handle on Spring's context. Is Spring running?"
              + "Check there's an org.springframework.web.context.ContextLoaderListener configured.");
    }

    String[] beanDefinitionNames = wac.getBeanDefinitionNames();
    for (String string : beanDefinitionNames) {
      System.out.println("SpringApplicationServlet.getNewApplication() ->" + string);
    }

    Application bean = wac.getBean(name, Application.class);

    if (!(bean instanceof Application)) {

      throw new ServletException("Bean " + name + " is not of expected class Application");
    }

    return bean;
  }
Пример #3
0
  public void init(ServletConfig servletConfig) throws ServletException {

    super.init(servletConfig);

    ServletContext sc = servletConfig.getServletContext();

    wac = WebApplicationContextUtils.getWebApplicationContext(sc);
    headerPreContent = servletConfig.getInitParameter("headerPreContent");
    headerScriptSource = servletConfig.getInitParameter("headerScriptSource");
    footerScript = servletConfig.getInitParameter("footerScript");
    try {
      boolean logResponse = "true".equalsIgnoreCase(servletConfig.getInitParameter("log-response"));
      TimeLogger.setLogResponse(logResponse);
    } catch (Exception ex) {

    }
    try {
      boolean logFullResponse =
          "true".equalsIgnoreCase(servletConfig.getInitParameter("log-full-response"));
      TimeLogger.setLogFullResponse(logFullResponse);
    } catch (Exception ex) {

    }

    String basePath = servletConfig.getServletContext().getRealPath("/");
    dispatcher = new MapDispatcher(sc);
  }
 public void init() throws ServletException {
   super.init();
   WebApplicationContext ctx =
       WebApplicationContextUtils.getWebApplicationContext(getServletContext());
   AutowireCapableBeanFactory factory = ctx.getAutowireCapableBeanFactory();
   factory.autowireBean(this);
 }
  public Principal login(Object credentials, String charset) {
    List<String> decodedCredentials = Arrays.asList(decodeBase64Credentials(credentials, charset));

    HttpGraniteContext context = (HttpGraniteContext) GraniteContext.getCurrentInstance();
    HttpServletRequest httpRequest = context.getRequest();

    String user = decodedCredentials.get(0);
    String password = decodedCredentials.get(1);
    Authentication auth = new UsernamePasswordAuthenticationToken(user, password);
    Principal principal = null;

    ApplicationContext ctx =
        WebApplicationContextUtils.getWebApplicationContext(
            httpRequest.getSession().getServletContext());
    if (ctx != null) {
      AbstractAuthenticationManager authenticationManager =
          BeanFactoryUtils.beanOfTypeIncludingAncestors(ctx, AbstractAuthenticationManager.class);
      try {
        Authentication authentication = authenticationManager.authenticate(auth);
        SecurityContext securityContext = SecurityContextHolder.getContext();
        securityContext.setAuthentication(authentication);
        principal = authentication;
        SecurityContextHolder.setContext(securityContext);
        saveSecurityContextInSession(securityContext, 0);

        endLogin(credentials, charset);
      } catch (AuthenticationException e) {
        handleAuthenticationExceptions(e);
      }
    }

    log.debug("User %s logged in", user);

    return principal;
  }
  @Override
  public void contextInitialized(ServletContextEvent event) {
    try {
      if (!isInit) {
        Platform.createComponentLoaderFromWebApplicationContext(
            WebApplicationContextUtils.getWebApplicationContext(event.getServletContext()));
        node = Platform.getComponentLoader().getComponent(ManagementNodeManager.class);
        bus = Platform.getComponentLoader().getComponent(CloudBus.class);
        node.startNode();
        isInit = true;
      }
    } catch (Throwable t) {
      logger.warn("failed to start management server", t);
      // have to call bus.stop() because its init has been called by spring
      if (bus != null) {
        bus.stop();
      }

      Throwable root = ExceptionDSL.getRootThrowable(t);
      new BootErrorLog().write(root.getMessage());
      if (CoreGlobalProperty.EXIT_JVM_ON_BOOT_FAILURE) {
        System.exit(1);
      } else {
        throw new CloudRuntimeException(t);
      }
    }
  }
Пример #7
0
 public void contextInitialized(ServletContextEvent event) {
   ServletContext context = event.getServletContext();
   initUserInterface(context);
   ApplusContext.setWebApplicationContext(
       WebApplicationContextUtils.getWebApplicationContext(event.getServletContext()));
   logger.debug("\ninitialized.");
 }
  public void contextInitialized(ServletContextEvent se) {
    // 完成项目启动数据的初始化功能
    // 1: 如果数据量不大,更新不频繁可以存储到app缓存中, 缺点: 需要自己解决同步问题
    // 2: 数据量大,可以考虑使用hibernate二级缓存, hibernate自己提供了同步功能
    // Spring的配置文件,项目启动的时候配置文件读取后也存储到了application内置对象中
    context = WebApplicationContextUtils.getWebApplicationContext(se.getServletContext());
    categoryService = (CategoryService) context.getBean("categoryService");
    fileUploadUtil = (FileUploadUtil) context.getBean("fileUploadUtil");
    privilegeService = (PrivilegeService) context.getBean("privilegeService");
    // 获取所有的类别,并且存储到application内置中
    se.getServletContext().setAttribute("categorys", categoryService.query());
    // 通过Spring配置文件,获取线程任务
    shopTimerTask = (ShopTimerTask) context.getBean("shopTimerTask");
    shopTimerTask.setApplication(se.getServletContext());
    // 设置执行时间
    new Timer(true).schedule(shopTimerTask, 0, 1000 * 60 * 1000);

    // 通过路径获取银行图标,并且存储到application内置对象中
    String path = se.getServletContext().getRealPath("/image/logo");
    se.getServletContext().setAttribute("bankImages", fileUploadUtil.bankImage(path));

    // 获取所有权限菜单数据,支持树状结构
    se.getServletContext().setAttribute("privileges", privilegeService.getPrivilegeMenu());

    // 获取所有的purls
    se.getServletContext().setAttribute("purls", privilegeService.getPrivilegeUrl());
  }
  /**
   * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
   *
   * @param request servlet request
   * @param response servlet response
   * @throws ServletException if a servlet-specific error occurs
   * @throws IOException if an I/O error occurs
   */
  protected void processRequest(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();

    try {

      ApplicationContext appContext =
          WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
      ceaService = appContext.getBean(ICountryEnvironmentApplicationService.class);
      factoryCea = appContext.getBean(IFactoryCountryEnvironmentApplication.class);
      PolicyFactory policy = Sanitizers.FORMATTING.and(Sanitizers.LINKS);

      String id = policy.sanitize(request.getParameter("id"));
      String system = id.split("System&#61;")[1].split("&amp;")[0];
      String country = id.split("Country&#61;")[1].split("&amp;")[0];
      String env = id.split("Env&#61;")[1].split("&amp;")[0];
      String app = id.split("App&#61;")[1].split("&amp;")[0];

      response.setContentType("text/html");
      ceaService.delete(factoryCea.create(system, country, env, app, null, null, null, null));
    } catch (CerberusException ex) {
      Logger.getLogger(DeleteCountryEnvironmentParameter.class.getName())
          .log(Level.SEVERE, null, ex);
    }
  }
Пример #10
0
  @Override
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    ApplicationContext appContext =
        WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
    campaignService = appContext.getBean(ICampaignService.class);
    PolicyFactory policy = Sanitizers.FORMATTING.and(Sanitizers.LINKS);

    String pk = policy.sanitize(request.getParameter("id"));
    String name = policy.sanitize(request.getParameter("columnName"));
    String value = policy.sanitize(request.getParameter("value"));

    response.setContentType("text/html");
    try {
      CampaignParameter campaignParameter =
          campaignService.findCampaignParameterByKey(Integer.parseInt(pk));
      if (name != null && "Value".equals(name.trim())) {
        campaignParameter.setValue(value);
      } else {
        throw new CerberusException(new MessageGeneral(MessageGeneralEnum.NOT_IMPLEMEMTED));
      }
      campaignService.updateCampaignParameter(campaignParameter);
      response.getWriter().print(value);
    } catch (CerberusException ex) {
      response.getWriter().print(ex.getMessageError().getDescription());
    }
  }
  @Override
  public void onStartup(Set<Class<?>> c, ServletContext ctx) throws ServletException {
    logger.info("==============================");

    if (null != c) {
      for (Iterator<Class<?>> iterator = c.iterator(); iterator.hasNext(); ) {
        Class<?> clazz = (Class<?>) iterator.next();

        StudyApplicationInitializer instance = null;
        try {
          instance = (StudyApplicationInitializer) clazz.newInstance();
        } catch (Exception e) {
          e.printStackTrace();
        }

        if (null != instance) {
          instance.onStartup(ctx);
        }

        WebApplicationContext wac = WebApplicationContextUtils.getWebApplicationContext(ctx);

        logger.info(clazz);
      }
    }

    logger.info("==============================");
  }
 @Override
 public void init() throws ServletException {
   ServletContext servletContext = this.getServletContext();
   WebApplicationContext webAppContext =
       WebApplicationContextUtils.getWebApplicationContext(servletContext);
   studentService = webAppContext.getBean(StudentService.class);
 }
  /**
   * Get the application class from the bean configured in Spring's context.
   *
   * @see AbstractApplicationServlet#getApplicationClass()
   */
  @Override
  protected Class<? extends Application> getApplicationClass() throws ClassNotFoundException {

    WebApplicationContext wac =
        WebApplicationContextUtils.getWebApplicationContext(getServletContext());

    if (wac == null) {
      throw new ClassNotFoundException(
          "Cannot get an handle on Spring's context. Is Spring running? "
              + "Check there's an org.springframework.web.context.ContextLoaderListener configured.");
    }
    String[] beanDefinitionNames = wac.getBeanDefinitionNames();
    for (String string : beanDefinitionNames) {
      System.out.println("SpringApplicationServlet.getApplicationClass() " + string);
    }

    Application bean = wac.getBean(name, Application.class);

    if (bean == null) {

      throw new ClassNotFoundException("No application bean found under name " + name);
    }

    return bean.getClass();
  }
 /**
  * Returns the messageSource bean configured in the applicationContext.xml file.
  *
  * @param request HttpServletRequest
  * @return messageSouce bean
  */
 public static MessageSource getMessageSource(HttpServletRequest request) {
   WebApplicationContext context =
       WebApplicationContextUtils.getWebApplicationContext(
           request.getSession(false).getServletContext());
   return (ResourceBundleMessageSource)
       context.getBean(ApplicationConstants.MESSAGE_SOURCE_BEAN_NAME);
 }
 @Override
 public void init() {
   if (applicationContext == null) {
     applicationContext = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
   }
   computerDatabaseService = applicationContext.getBean(ComputerDatabaseService.class);
 }
Пример #16
0
 public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
     throws IOException, ServletException {
   HttpSession session = ((HttpServletRequest) request).getSession(true);
   Authn authnService =
       (Authn)
           WebApplicationContextUtils.getWebApplicationContext(session.getServletContext())
               .getBean(authnBean);
   String userUid = null;
   try {
     userUid = authnService.getUserUid(request);
   } catch (Exception e) {
     if (log.isDebugEnabled()) log.debug("Could not get user uuid from authn service.");
   }
   if (log.isDebugEnabled()) log.debug("userUid=" + userUid);
   if (userUid == null) {
     if (authnRedirect != null) {
       if (authnRedirect.equals(((HttpServletRequest) request).getRequestURI())) {
         // Don't redirect to the same spot.
         chain.doFilter(request, response);
       } else {
         ((HttpServletResponse) response).sendRedirect(authnRedirect);
       }
     } else {
       ((HttpServletResponse) response).sendError(HttpServletResponse.SC_UNAUTHORIZED);
     }
   } else {
     chain.doFilter(request, response);
   }
 }
  protected WebApplicationContext createWebApplicationContext(WebApplicationContext parent)
      throws BeansException {
    WebApplicationContext wac =
        WebApplicationContextUtils.getWebApplicationContext(getServletContext());
    WebApplicationContext webContext;
    // construct the SpringConfig for the container managed application
    Assert.notNull(
        parent,
        "Grails requires a parent ApplicationContext, is the /WEB-INF/applicationContext.xml file missing?");
    this.application =
        (GrailsApplication)
            parent.getBean(GrailsApplication.APPLICATION_ID, GrailsApplication.class);

    if (wac instanceof GrailsApplicationContext) {
      webContext = wac;
    } else {
      webContext = GrailsConfigUtils.configureWebApplicationContext(getServletContext(), parent);
      try {
        GrailsConfigUtils.executeGrailsBootstraps(application, webContext, getServletContext());
      } catch (Exception e) {
        GrailsUtil.deepSanitize(e);
        if (e instanceof BeansException) throw (BeansException) e;
        else {
          throw new BootstrapException("Error executing bootstraps", e);
        }
      }
    }

    initMainController(webContext);
    this.interceptors = establishInterceptors(webContext);

    return webContext;
  }
 @Override
 public void init() throws ServletException {
   ServletContext application = this.getServletContext();
   WebApplicationContext context =
       WebApplicationContextUtils.getWebApplicationContext(application);
   this.abstractMainService = (AbstractMainService) context.getBean("abstractMainService");
 }
Пример #19
0
 @Override
 public void init(FilterConfig filterConfig) throws ServletException {
   WebApplicationContext context =
       WebApplicationContextUtils.getWebApplicationContext(filterConfig.getServletContext());
   this.userManagementService = context.getBean(UserManagementService.class);
   this.employeeManagementService = context.getBean(EmployeeManagementService.class);
   this.objectMapper = context.getBean(ObjectMapper.class);
 }
 public void contextInitialized(ServletContextEvent event) {
   super.contextInitialized(event);
   WebApplicationContext wac =
       WebApplicationContextUtils.getWebApplicationContext(event.getServletContext());
   IFunctionService resourceService = (IFunctionService) wac.getBean("functionService");
   resourceService.findAllUrl();
   event.getServletContext().setAttribute(Constants.APP_MANAGER_THEME, "default");
 }
Пример #21
0
 private void showMainPage(HttpServletRequest req, HttpServletResponse resp)
     throws ServletException, IOException {
   WebApplicationContext context =
       WebApplicationContextUtils.getWebApplicationContext(getServletContext());
   req.setAttribute("quote", quote.getRandomQuote());
   req.setAttribute("categoryList", category.getCategoryList().values());
   req.getRequestDispatcher("main.jsp").forward(req, resp);
 }
Пример #22
0
  public static ApplicationContext getApplicationContext() {
    ServletContext servletContext = ServletActionContext.getServletContext();
    if (servletContext == null) {
      throw new NullPointerException("This method can be called only within servlet environment.");
    }

    return WebApplicationContextUtils.getWebApplicationContext(servletContext);
  }
 public static void updateURL(String newURL, ServletContext servletContext) throws Exception {
   WebApplicationContext context =
       WebApplicationContextUtils.getWebApplicationContext(servletContext);
   Map<String, ServerBeanPropertyUpdater> updaters =
       context.getBeansOfType(ServerBeanPropertyUpdater.class);
   for (ServerBeanPropertyUpdater updater : updaters.values()) {
     updater.updateServerURL(newURL);
   }
 }
  /**
   * Initialize and publish the WebApplicationContext for this servlet.
   *
   * <p>Delegates to {@link #createWebApplicationContext} for actual creation of the context. Can be
   * overridden in subclasses.
   *
   * @return the WebApplicationContext instance
   * @see #FrameworkServlet(WebApplicationContext)
   * @see #setContextClass
   * @see #setContextConfigLocation
   */
  protected WebApplicationContext initWebApplicationContext() {
    WebApplicationContext rootContext =
        WebApplicationContextUtils.getWebApplicationContext(getServletContext());
    WebApplicationContext wac = null;

    if (this.webApplicationContext != null) {
      // A context instance was injected at construction time -> use it
      wac = this.webApplicationContext;
      if (wac instanceof ConfigurableWebApplicationContext) {
        ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext) wac;
        if (!cwac.isActive()) {
          // The context has not yet been refreshed -> provide services such as
          // setting the parent context, setting the application context id, etc
          if (cwac.getParent() == null) {
            // The context instance was injected without an explicit parent -> set
            // the root application context (if any; may be null) as the parent
            cwac.setParent(rootContext);
          }
          configureAndRefreshWebApplicationContext(cwac);
        }
      }
    }
    if (wac == null) {
      // No context instance was injected at construction time -> see if one
      // has been registered in the servlet context. If one exists, it is assumed
      // that the parent context (if any) has already been set and that the
      // user has performed any initialization such as setting the context id
      wac = findWebApplicationContext();
    }
    if (wac == null) {
      // No context instance is defined for this servlet -> create a local one
      wac = createWebApplicationContext(rootContext);
    }

    if (!this.refreshEventReceived) {
      // Either the context is not a ConfigurableApplicationContext with refresh
      // support or the context injected at construction time had already been
      // refreshed -> trigger initial onRefresh manually here.
      onRefresh(wac);
    }

    if (this.publishContext) {
      // Publish the context as a servlet context attribute.
      String attrName = getServletContextAttributeName();
      getServletContext().setAttribute(attrName, wac);
      if (this.logger.isDebugEnabled()) {
        this.logger.debug(
            "Published WebApplicationContext of servlet '"
                + getServletName()
                + "' as ServletContext attribute with name ["
                + attrName
                + "]");
      }
    }

    return wac;
  }
Пример #25
0
 @Override
 public void contextInitialized(ServletContextEvent servletContextEvent) {
   applicationContext =
       WebApplicationContextUtils.getWebApplicationContext(
           servletContextEvent.getServletContext());
   logger.info("-----------------------------InitDataListener   init ----------------------");
   initTask = (InitTask) applicationContext.getBean("initTask");
   initTask.run();
 }
Пример #26
0
 @Override
 public void init(ServletConfig config) throws ServletException {
   super.init(config);
   ApplicationContext context =
       WebApplicationContextUtils.getWebApplicationContext(config.getServletContext());
   portalPageAdapter = context.getBean(PortalPageAdapter.class);
   this.portalDataMarshaller = context.getBean(PortalDataExporter.class);
   logger.debug("initialized " + this);
 }
  /** 初始化. */
  @Override
  public void init() throws ServletException {
    // 保存applicationContext以备后用,纯演示.
    applicationContext = WebApplicationContextUtils.getWebApplicationContext(getServletContext());

    // 初始化mimeTypes, 默认缺少css的定义,添加之.
    mimetypesFileTypeMap = new MimetypesFileTypeMap();
    mimetypesFileTypeMap.addMimeTypes("text/css css");
  }
Пример #28
0
  @Override
  public void init(ServletConfig servletConfig) throws ServletException {

    super.init(servletConfig);

    ApplicationContext applicationContext =
        WebApplicationContextUtils.getWebApplicationContext(servletConfig.getServletContext());
    if (applicationContext != null) this.setApplicationContext(applicationContext);
  }
Пример #29
0
  public void contextInitialized(ServletContextEvent sce) {

    ApplicationContext ctx =
        WebApplicationContextUtils.getWebApplicationContext(sce.getServletContext());

    schedulerService = ctx.getBean(JobSchedulerService.class);
    properties = (Properties) ctx.getBean("properties");

    logger.info("ShutdownListener initialized");
  }
  @Override
  public void init() throws ServletException {
    super.init();

    ServletContext servletContext = this.getServletContext();

    WebApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(servletContext);

    sessionFactory = (SessionFactory) ctx.getBean("sessionFactory");
  }