Example #1
0
 public void Install() {
   ServletContext sc = getServletContext();
   WebApplicationContext ac = WebApplicationContextUtils.getRequiredWebApplicationContext(sc);
   RealPathResolver realPathResolver = (RealPathResolver) ac.getBean("realPathResolver");
   UpdateMng updateMng = (UpdateMng) ac.getBean("updateMng");
   updateMng.update();
   String dbXmlFileName = "/WEB-INF/classes/jdbc.properties";
   String url, dbUser, dbPassword;
   InputStream in;
   try {
     in = new FileInputStream(realPathResolver.get(dbXmlFileName));
     Properties p = new Properties();
     p.load(in);
     url = p.getProperty("jdbc.url");
     String[] urls = url.split("[?]");
     dbUser = p.getProperty("jdbc.username");
     dbPassword = p.getProperty("jdbc.password");
     createTable(urls[0], dbUser, dbPassword);
   } catch (FileNotFoundException e) {
     e.printStackTrace();
   } catch (IOException e) {
     e.printStackTrace();
   } catch (Exception e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   }
 }
  /**
   * Executes Grails bootstrap classes
   *
   * @param application The Grails ApplicationContext instance
   * @param webContext The WebApplicationContext instance
   * @param servletContext The ServletContext instance
   */
  public static void executeGrailsBootstraps(
      GrailsApplication application,
      WebApplicationContext webContext,
      ServletContext servletContext) {

    PersistenceContextInterceptor interceptor = null;
    String[] beanNames = webContext.getBeanNamesForType(PersistenceContextInterceptor.class);
    if (beanNames.length > 0) {
      interceptor = (PersistenceContextInterceptor) webContext.getBean(beanNames[0]);
    }

    if (interceptor != null) {
      interceptor.init();
    }
    // init the Grails application
    try {
      GrailsClass[] bootstraps = application.getArtefacts(BootstrapArtefactHandler.TYPE);
      for (GrailsClass bootstrap : bootstraps) {
        final GrailsBootstrapClass bootstrapClass = (GrailsBootstrapClass) bootstrap;
        final Object instance = bootstrapClass.getReferenceInstance();
        webContext
            .getAutowireCapableBeanFactory()
            .autowireBeanProperties(instance, AutowireCapableBeanFactory.AUTOWIRE_BY_NAME, false);
        bootstrapClass.callInit(servletContext);
      }
      if (interceptor != null) {
        interceptor.flush();
      }
    } finally {
      if (interceptor != null) {
        interceptor.destroy();
      }
    }
  }
  @Test
  public void pathVarsInModel() throws Exception {
    final Map<String, Object> pathVars = new HashMap<String, Object>();
    pathVars.put("hotel", "42");
    pathVars.put("booking", 21);
    pathVars.put("other", "other");

    WebApplicationContext wac =
        initDispatcherServlet(
            ViewRenderingController.class,
            new BeanDefinitionRegistrar() {
              public void register(GenericWebApplicationContext context) {
                RootBeanDefinition beanDef =
                    new RootBeanDefinition(ModelValidatingViewResolver.class);
                beanDef.getConstructorArgumentValues().addGenericArgumentValue(pathVars);
                context.registerBeanDefinition("viewResolver", beanDef);
              }
            });

    MockHttpServletRequest request =
        new MockHttpServletRequest("GET", "/hotels/42/bookings/21-other");
    servlet.service(request, new MockHttpServletResponse());

    ModelValidatingViewResolver resolver = wac.getBean(ModelValidatingViewResolver.class);
    assertEquals(3, resolver.validatedAttrCount);
  }
Example #4
0
 @Override
 public void init(FilterConfig filterConfig) throws ServletException {
   WebApplicationContext ctx = getRequiredWebApplicationContext(filterConfig.getServletContext());
   this.configurationRepository = ctx.getBean(ConfigurationRepository.class);
   this.users = ctx.getBean(Users.class);
   this.sessionHandler = ctx.getBean(SessionHandler.class);
 }
 public void init() throws ServletException {
   super.init();
   WebApplicationContext ctx =
       WebApplicationContextUtils.getWebApplicationContext(getServletContext());
   AutowireCapableBeanFactory factory = ctx.getAutowireCapableBeanFactory();
   factory.autowireBean(this);
 }
Example #6
0
 /**
  *
  * <pre>
  * 方法体说明:合同申请---判断发票标记类型
  * 作者:andy
  * 日期: 2013-11-25 上午14:18:21
  * @param map
  * @return:1-true,否则false
  * </pre>
  */
 public boolean isType(Map<?, ?> map) {
   // 根据业务编码获取合同信息
   ContractWorkflowInfo info = new ContractWorkflowInfo();
   // 获得业务编码
   String bizCode = (String) map.get(BPMSConstant.BIZCODE); // 流程实例ID
   // 获得流程定义名称
   String processDefName = map.get(BPMSConstant.PROCESS_DEF_NAME).toString();
   // 获得WebApplicationContext
   WebApplicationContext wac = WebApplicationContextHolder.getWebApplicationContext();
   // 得到合同工作流manager
   IContractWorkflowManager contractWorkflowManager =
       (IContractWorkflowManager) wac.getBean("contractWorkflowManager");
   // 根据工作流业务编码及流程定义名称查询出合同详细信息
   info = contractWorkflowManager.findContractWorkflowInfoByWorkNo(bizCode, processDefName);
   // 如果对应的合同信息不为空
   if (null != info & StringUtil.isNotEmpty(info.getContractNumber())) {
     // 发票标记为01 返回true
     if (Constant.INVOICE_TYPE_01.equals(info.getInvoiceType())) {
       return true;
     } else {
       return false;
     }
   }
   return false;
 }
 /**
  * 保障评分
  *
  * @param mapping
  * @param form
  * @param request
  * @param response
  * @return
  */
 public ActionForward examSafeguard(
     ActionMapping mapping,
     ActionForm form,
     HttpServletRequest request,
     HttpServletResponse response) {
   WebApplicationContext ctx = getWebApplicationContext();
   SafeguardTaskBo stb = (SafeguardTaskBo) ctx.getBean("safeguardTaskBo");
   UserInfo userInfo = (UserInfo) request.getSession().getAttribute("LOGIN_USER");
   SafeguardExamBean safeguardExamBean = (SafeguardExamBean) form;
   // 获得日常考核对象
   AppraiseDailyBean appraiseDailyBean =
       (AppraiseDailyBean) request.getSession().getAttribute("appraiseDailyDailyBean");
   List<AppraiseDailyBean> speicalBeans =
       (List<AppraiseDailyBean>) request.getSession().getAttribute("appraiseDailySpecialBean");
   String taskId = safeguardExamBean.getTaskId();
   String name = stb.get(taskId).getSafeguardName();
   try {
     getSafeguardExamBo()
         .examSafeguard(safeguardExamBean, userInfo, appraiseDailyBean, speicalBeans);
     log(request, "保障评分(保障名称为: " + name + ")", "保障管理");
     return forwardInfoPage(mapping, request, "examSafeguardSuccess");
   } catch (ServiceException e) {
     logger.error("保障评分出错,出错信息:" + e.getMessage());
     return forwardErrorPage(mapping, request, "examSafeguardError");
   }
 }
Example #8
0
 /**
  *
  * <pre>
  * 方法体说明:结算限额判断
  * 作者:andy
  * 日期: 2013-11-25 下午14:18:21
  * @param map
  * @param mcDefiniTionName
  * @return:是则返回true,否则false
  * </pre>
  */
 private boolean isBalanceAccount(Map<?, ?> map, String mcDefiniTionName) {
   double balanceAccount = 0; // 结算限额
   ContractWorkflowInfo info = new ContractWorkflowInfo();
   String bizCode = (String) map.get(BPMSConstant.BIZCODE); // 流程实例ID
   String currentActivityDefId = map.get(BPMSConstant.CURRENT_ACTIVITY_DEF_ID).toString(); // 当前节点
   String nextActivityDefId = map.get(BPMSConstant.NEXT_ACTIVITY_DEF_ID).toString(); // 下一节点
   WebApplicationContext wac = WebApplicationContextHolder.getWebApplicationContext();
   IContractWorkflowManager contractWorkflowManager =
       (IContractWorkflowManager) wac.getBean("contractWorkflowManager");
   IAmountConfigService amountConfigService =
       (IAmountConfigService) wac.getBean("bpsAmountConfigService");
   info = contractWorkflowManager.findContractWorkflowInfoByWorkNo(bizCode, mcDefiniTionName);
   balanceAccount = Double.valueOf(info.getBalanceAccount());
   if (BpsConstant.EX_UPDATE_PROCESSNAME.equals(mcDefiniTionName)
       || BpsConstant.LTT_UPDATE_PROCESSNAME.equals(mcDefiniTionName)) {
     balanceAccount = Double.valueOf(info.getNewBalanceAccount());
   }
   BigDecimal amount = new BigDecimal(balanceAccount);
   AmountConfigEntity amountConfigEntity = new AmountConfigEntity();
   amountConfigEntity.setCurrentApproStepNo(currentActivityDefId);
   amountConfigEntity.setTargetApproStepNo(nextActivityDefId);
   amountConfigEntity.setMcDefiniTionName(mcDefiniTionName);
   AmountConfigEntity entity = amountConfigService.queryForBranch(amountConfigEntity);
   if (entity != null) {
     BigDecimal minAmount = entity.getMinAmount();
     BigDecimal maxAmount = entity.getMaxAmount();
     if (amount.compareTo(minAmount) > 0 && amount.compareTo(maxAmount) <= 0) {
       return true;
     }
   }
   return false;
 }
Example #9
0
 /**
  *
  * <pre>
  * 方法体说明:判断是否快递大区
  * 作者:andy
  * 日期: 2013-11-25 上午14:18:21
  * @param map
  * @return:是则返回true,否则false
  * </pre>
  */
 public boolean isExpressArea(Map<?, ?> map) {
   ContractWorkflowInfo info = new ContractWorkflowInfo();
   String bizCode = (String) map.get(BPMSConstant.BIZCODE); // 流程实例ID
   String processDefName = map.get(BPMSConstant.PROCESS_DEF_NAME).toString();
   WebApplicationContext wac = WebApplicationContextHolder.getWebApplicationContext();
   IContractWorkflowManager contractWorkflowManager =
       (IContractWorkflowManager) wac.getBean("contractWorkflowManager");
   IDepartmentService departmentService = (IDepartmentService) wac.getBean("departmentService");
   info = contractWorkflowManager.findContractWorkflowInfoByWorkNo(bizCode, processDefName);
   if (null != info & StringUtil.isNotEmpty(info.getContractNumber())) {
     // 点部标杆编码
     String expressPointDeptCode = info.getExpressPointDeptCode();
     // 如果编码不为空
     if (StringUtil.isNotEmpty(expressPointDeptCode)) {
       // 查询出对应的快递点部
       Department exDept = departmentService.getDeptByStandardCode(expressPointDeptCode);
       Department bigArea = null;
       if (null != exDept) {
         bigArea = departmentService.getBigAreaByDeptId(exDept.getId());
       }
       if (bigArea != null && !StringUtil.isEmpty(bigArea.getId())) {
         List<Department> deptList = departmentService.queryAllChildDeptByDeptId(bigArea.getId());
         for (int i = 0; i < deptList.size(); i++) {
           Department deptment = deptList.get(i);
           // 如果子部门有快递部分 则改部门不是快递大区
           if (deptment != null && deptment.getDeptName().endsWith("快递分部")) { // 有快递分部,则无快递事业部
             return false;
           }
         }
         return true;
       }
     }
   }
   return false;
 }
  public void execute(JobExecutionContext arg) throws JobExecutionException {
    logger.entering(new Object[0]);

    WebApplicationContext context = QuartzServletContextListener.getSpringApplicationContext();
    AtendimentoFacade atendimentoFacade = (AtendimentoFacade) context.getBean("atendimentoFacade");
    AlertaFacade alertaFacade = (AlertaFacade) context.getBean("alertaFacade");
    Alerta alerta = (Alerta) arg.getJobDetail().getJobDataMap().get("alerta");
    alerta = alertaFacade.get(alerta.getId(), true);
    List<Atendimento> atendimentos = new ArrayList();
    if ((alerta.getEscalonamentos() != null) && (!alerta.getEscalonamentos().isEmpty())) {
      for (Escalonamento es : alerta.getEscalonamentos()) {
        atendimentos =
            atendimentoFacade.getAtendimentoPorTempo(
                es.getTempo(), es.getUnidade(), alerta.getProblemas());
        List emails = null;
        if ((atendimentos != null) && (!atendimentos.isEmpty())) {
          StringBuilder sb = new StringBuilder();
          sb.append("<br />");
          for (Atendimento atn : atendimentos) {
            sb.append(montaMsg(atn));
            sb.append("<br />");
            emails = recuperaEmail(es, atn);
          }
          String msg =
              MessagesUtil.matchAndReplace(
                  MessagesUtil.getMessage("MessageResources", "msg.alertas.atrasados"),
                  new Object[] {es.getTempo().toString(), es.getUnidade(), sb.toString()});
          enviaEmails(emails, msg);
        }
      }
    }
    logger.exiting(new Object[0]);
  }
Example #11
0
 @Override
 public void doTag() throws JspException, IOException {
   if (org == null) { // 如果标签的org属性没有值则读取数据库取得组织结构信息
     ServletContext servletContext = ((PageContext) this.getJspContext()).getServletContext();
     WebApplicationContext ctx =
         WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
     OrgService orgService = (OrgService) ctx.getBean("orgService");
     this.setOrg(orgService.findRoot());
   }
   // 生成第一层组织结构
   List<OrgProfile> orgList = this.getOrg().getChildren();
   StringBuffer html = new StringBuffer();
   if (this.getTopOrgClass() == null) {
     html.append("<ul>");
   } else {
     html.append("<ul class=\"").append(this.getTopOrgClass()).append("\">");
   }
   for (OrgProfile orgItem : orgList) {
     html.append("<li>");
     html.append("<a id=\"")
         .append(orgItem.getId())
         .append("\" href=\"#\">")
         .append(orgItem.getName())
         .append("</a>");
     // 递归生成组织结构
     html.append(this.writeHTML(orgItem));
     html.append("</li>");
   }
   html.append("</ul>");
   try {
     getJspContext().getOut().print(html);
   } catch (Exception ex) {
     log.error("orgtree's tag error.", ex);
   }
 }
  protected void inject() {
    WebApplicationContext applicationContext = getApplicationContext();

    applicationContext
        .getAutowireCapableBeanFactory()
        .autowireBeanProperties(this, AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, false);
  }
Example #13
0
  public void prepare() throws Exception {
    logger.debug("Inside PatientProfile:prepare()");
    try {
      WebApplicationContext context =
          WebApplicationContextUtils.getRequiredWebApplicationContext(
              ServletActionContext.getServletContext());
      userService = (UserService) context.getBean("userService");
      auditInfoService = (AuditInfoService) context.getBean("auditInfoService");
      patientService = (PatientService) context.getBean("patientService");
      contactService = (ContactService) context.getBean("contactService");
      logger.debug("In prepare patientService =" + patientService);
      // is client behind something?
      ipAddress = request.getHeader("X-FORWARDED-FOR");
      if (ipAddress == null) {
        ipAddress = request.getRemoteAddr();
      }
      logger.debug("client's ipAddress =" + ipAddress);
      Object obj = request.getSession().getAttribute("user");
      if (obj != null) {
        userInSession = (UserVO) obj;
      }
      logger.debug("userInSession is " + userInSession.getAttributesAsString());
      //			path = context.getServletContext().getRealPath("/");
      //			String app = context.getServletContext().getContextPath();
      //			path = path.substring(0, path.lastIndexOf(app.split("/")[1]));

    } catch (Exception e) {
      e.printStackTrace();
    }
    logger.debug("Completing PatientProfile:prepare()");
  }
 @Override
 public void init() throws ServletException {
   ServletContext servletContext = this.getServletContext();
   WebApplicationContext webAppContext =
       WebApplicationContextUtils.getWebApplicationContext(servletContext);
   studentService = webAppContext.getBean(StudentService.class);
 }
Example #15
0
 public void setServlet(ActionServlet actionServlet) {
   super.setServlet(actionServlet);
   ServletContext servletContext = actionServlet.getServletContext();
   WebApplicationContext wac =
       WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
   this.petStore = (PetStoreFacade) wac.getBean("petStore");
 }
  public int doStartTagInternal() throws JspException {
    try {

      if (filePathUtils == null || imageUtils == null) {
        WebApplicationContext wac = getRequestContext().getWebApplicationContext();
        AutowireCapableBeanFactory factory = wac.getAutowireCapableBeanFactory();
        factory.autowireBean(this);
      }

      HttpServletRequest request = (HttpServletRequest) pageContext.getRequest();

      MerchantStore merchantStore = (MerchantStore) request.getAttribute(Constants.ADMIN_STORE);

      StringBuilder imagePath = new StringBuilder();

      String baseUrl = filePathUtils.buildStoreUri(merchantStore, request);
      imagePath.append(baseUrl);

      pageContext.getOut().print(imagePath.toString());

    } catch (Exception ex) {
      LOGGER.error("Error while getting content url", ex);
    }
    return SKIP_BODY;
  }
Example #17
0
 public void init(ServletConfig config) throws ServletException {
   super.init(config);
   ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(config.getServletContext());
   dao = (DerbyDao) ctx.getBean("personDao");
   txManager = (PlatformTransactionManager) ctx.getBean("transactionManager");
   dao.createTable();
 }
  private String getBeanNameByType(WebApplicationContext wac, Class<?> endpointClass) {

    String wacId = wac.getId();

    Map<Class<?>, String> beanNamesByType = cache.get(wacId);
    if (beanNamesByType == null) {
      beanNamesByType = new ConcurrentHashMap<Class<?>, String>();
      cache.put(wacId, beanNamesByType);
    }

    if (!beanNamesByType.containsKey(endpointClass)) {
      String[] names = wac.getBeanNamesForType(endpointClass);
      if (names.length == 1) {
        beanNamesByType.put(endpointClass, names[0]);
      } else {
        beanNamesByType.put(endpointClass, NO_VALUE);
        if (names.length > 1) {
          String message =
              "Found multiple @ServerEndpoint's of type " + endpointClass + ", names=" + names;
          logger.error(message);
          throw new IllegalStateException(message);
        }
      }
    }

    String beanName = beanNamesByType.get(endpointClass);
    return NO_VALUE.equals(beanName) ? null : beanName;
  }
  /**
   * Evalutes the given WebApplicationContext for all HandlerInterceptor and WebRequestInterceptor
   * instances
   *
   * @param webContext The WebApplicationContext
   * @return An array of HandlerInterceptor instances
   */
  protected HandlerInterceptor[] establishInterceptors(WebApplicationContext webContext) {
    HandlerInterceptor[] interceptors;
    String[] interceptorNames = webContext.getBeanNamesForType(HandlerInterceptor.class);
    String[] webRequestInterceptors = webContext.getBeanNamesForType(WebRequestInterceptor.class);
    interceptors = new HandlerInterceptor[interceptorNames.length + webRequestInterceptors.length];

    // Merge the handler and web request interceptors into a single
    // array. Note that we start with the web request interceptors
    // to ensure that the OpenSessionInViewInterceptor (which is a
    // web request interceptor) is invoked before the user-defined
    // filters (which are attached to a handler interceptor). This
    // should ensure that the Hibernate session is in the proper
    // state if and when users access the database within their
    // filters.
    int j = 0;
    for (int i = 0; i < webRequestInterceptors.length; i++) {
      interceptors[j++] =
          new WebRequestHandlerInterceptorAdapter(
              (WebRequestInterceptor) webContext.getBean(webRequestInterceptors[i]));
    }
    for (int i = 0; i < interceptorNames.length; i++) {
      interceptors[j++] = (HandlerInterceptor) webContext.getBean(interceptorNames[i]);
    }
    return interceptors;
  }
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    log.info("HelloServlet doGet");

    ServletContext servletContext = this.getServletContext();
    WebApplicationContext wac =
        WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
    personService = (PersonService) wac.getBean("personService");

    Person person = new Person();
    person.setFirst_name("Lee");
    person.setLast_name("Brian");

    person = personService.create(person);

    log.info("persion id created -> " + person.getEmplid());

    log.info("person -> " + personService.findByEmplid(person.getEmplid()));

    personService.delete(person);

    log.info("person deleted id -> " + person.getEmplid());

    response.setContentType("text/html");
    response.setStatus(HttpServletResponse.SC_OK);
    response.getWriter().println("<h1>Hello Servlet</h1>");
    response.getWriter().println("session=" + request.getSession(true).getId());
  }
 @Override
 public void init() throws ServletException {
   ServletContext application = this.getServletContext();
   WebApplicationContext context =
       WebApplicationContextUtils.getWebApplicationContext(application);
   this.abstractMainService = (AbstractMainService) context.getBean("abstractMainService");
 }
Example #22
0
 @Override
 public void init(FilterConfig filterConfig) throws ServletException {
   WebApplicationContext webApplicationContext =
       WebApplicationContextUtils.getRequiredWebApplicationContext(
           filterConfig.getServletContext());
   menuCache = (MenuCache) webApplicationContext.getBean("menuCache");
 }
Example #23
0
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    WebApplicationContext ctx =
        WebApplicationContextUtils.getRequiredWebApplicationContext(this.getServletContext());
    CourseManager manager = (CourseManager) ctx.getBean("courseManager");

    InternetAddress addr;
    InternetAddress address[] = new InternetAddress[1];
    addr = new InternetAddress("*****@*****.**", "cust", "BIG5");
    address[0] = addr;

    manager.sendMail(
        "",
        "",
        "www.cust.edu.tw",
        "*****@*****.**",
        "王小明",
        new Date(),
        "測試",
        "<img src='http://192.192.237.19/CIS/CountImage?userid=77'>",
        address,
        null);

    // response.setContentType("image/jpeg");
    // response.sendRedirect("/CIS/pages/images/transparent.gif");
  }
    /*
     * 创建事件 业务部分写在pullEvent()方法中,这个方法会被定时调用。
     */
    @Override
    protected Event pullEvent() {
      Event event = Event.createDataEvent("/notify/message");

      int count = SessionManager.getInstance().getSessionCount();
      if (count >= 1) {
        Session[] sessions = SessionManager.getInstance().getSessions();
        String userId = sessions[0].getEvent().getField("user_id");

        WebApplicationContext context = SpringContextHolder.getContext();
        NotifyMessageService notifyService =
            (NotifyMessageService) context.getBean("notifyService");

        NotifyMessage entity = new NotifyMessage();
        entity.setIs_query(false);
        entity.setIs_read(false);
        entity.setReceiver_id(Integer.parseInt(userId));
        Map<Integer, List<NotifyMessage>> map = notifyService.modifyAndQueryMapList(entity);
        try {
          String data = buildText(map);
          event.setField("data", data);
        } catch (Exception ex) {
          LogHelper.getLogger().error("构建事务通知信息时出错", ex);
        }

        // 在线用户
        event.setField("userCount", OnlineUser.getInstance().gainUserCount());
      }

      return event;
    }
 /**
  * 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);
 }
  /**
   * 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();
  }
Example #27
0
 @Override
 public void init(ServletConfig config) throws ServletException {
   super.init(config);
   WebApplicationContext context =
       WebApplicationContextUtils.getRequiredWebApplicationContext(config.getServletContext());
   jookService = (JookService) context.getBean(Jook.SPRING_BEAN_NAME_JOOK_SERVICE);
 }
  @Test
  @DirtiesContext
  public void changeGetBlogPage() throws Exception {
    UserStorage userStorage = wac.getBean("userStorage", UserStorage.class);
    BlogEntryStorage blogStorage = wac.getBean("blogEntryStorage", BlogEntryStorage.class);
    User user = new User("admin", "system");
    userStorage.saveOrUpdate(user);

    BlogEntry entryA = new BlogEntry("", "This is message A.", user);
    BlogEntry entryB = new BlogEntry("", "This is message B.", user);
    blogStorage.saveOrUpdate(entryA);
    blogStorage.saveOrUpdate(entryB);

    // let's check if we can change the entry by forging our own post request
    this.mockMvc
        .perform(
            post("/blog/update/" + entryA.getId())
                .param("text", "this is a blog entry")
                .param("tags", "a b")
                .param("authorId", "user"))
        .andExpect(view().name("blog/update"));

    List<String> expectedTags = new LinkedList<String>();
    expectedTags.add("a");
    expectedTags.add("b");
    BlogEntry newEntry = blogStorage.byId(entryA.getId());
    assertEquals(entryA.getAuthorId(), newEntry.getAuthorId());
    assertEquals(expectedTags, newEntry.getTags());
    assertEquals(entryA.getText(), newEntry.getText());
  }
  /**
   * 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;
  }
Example #30
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);
 }