Пример #1
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);
 }
Пример #2
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;
 }
Пример #3
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();
   }
 }
Пример #4
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;
 }
Пример #5
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()");
  }
  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]);
  }
  /**
   * 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;
  }
Пример #8
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();
 }
  @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());
  }
Пример #10
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);
 }
Пример #11
0
 @Override
 public void init(ServletConfig config) throws ServletException {
   super.init(config);
   WebApplicationContext wac =
       WebApplicationContextUtils.getRequiredWebApplicationContext(config.getServletContext());
   factory = (NotificationFactory) wac.getBean("notificationFactory");
   emailService = (NotificationService) wac.getBean("emailService");
   smsService = (NotificationService) wac.getBean("smsService");
 }
 @Test
 public void testApplicationScope() {
   WebApplicationContext ac = initApplicationContext(WebApplicationContext.SCOPE_APPLICATION);
   assertNull(ac.getServletContext().getAttribute(NAME));
   DerivedTestBean bean = ac.getBean(NAME, DerivedTestBean.class);
   assertSame(bean, ac.getServletContext().getAttribute(NAME));
   assertSame(bean, ac.getBean(NAME));
   new ContextCleanupListener().contextDestroyed(new ServletContextEvent(ac.getServletContext()));
   assertTrue(bean.wasDestroyed());
 }
Пример #13
0
 protected Object displayTemplate(String fileUri, Object dataModel) throws Exception {
   Template template =
       webApplicationContext
           .getBean(FreeMarkerConfigurer.class)
           .getConfiguration()
           .getTemplate(
               moduleName
                   + "/"
                   + fileUri
                   + webApplicationContext.getBean(Configuration.class).getTemplateSuffix());
   Writer out = new OutputStreamWriter(response.getOutputStream());
   template.process(dataModel, out);
   return null;
 }
Пример #14
0
 public void init(ServletConfig servletConfig) throws ServletException {
   ServletContext servletContext = servletConfig.getServletContext();
   // 获取Spring上下文
   WebApplicationContext webApplicationContext =
       WebApplicationContextUtils.getWebApplicationContext(servletContext);
   // 用户组和用户数据
   IdentityService identityService =
       (IdentityService) webApplicationContext.getBean("identityService");
   initGroupsAndUsers(identityService);
   // 部署流程
   RepositoryService repositoryService =
       (RepositoryService) webApplicationContext.getBean("repositoryService");
   initProcessDefinition(repositoryService);
 }
 @Override
 protected Application getNewApplication(HttpServletRequest request) throws ServletException {
   if (logger.isTraceEnabled()) {
     logger.trace("getNewApplication()");
   }
   return (Application) applicationContext.getBean(applicationBean);
 }
 @Override
 public void init() throws ServletException {
   ServletContext application = this.getServletContext();
   WebApplicationContext context =
       WebApplicationContextUtils.getWebApplicationContext(application);
   this.abstractMainService = (AbstractMainService) context.getBean("abstractMainService");
 }
Пример #17
0
  private Object getBeanByWebCtx(String beanName) throws Exception {
    if (null == webCtx) {
      return null;
    }

    return webCtx.getBean(beanName);
  }
  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;
  }
 /**
  * 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);
 }
Пример #20
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);
 }
 @Override
 public void init() throws ServletException {
   ServletContext servletContext = this.getServletContext();
   WebApplicationContext webAppContext =
       WebApplicationContextUtils.getWebApplicationContext(servletContext);
   studentService = webAppContext.getBean(StudentService.class);
 }
Пример #22
0
 @Override
 public void init(FilterConfig filterConfig) throws ServletException {
   WebApplicationContext webApplicationContext =
       WebApplicationContextUtils.getRequiredWebApplicationContext(
           filterConfig.getServletContext());
   menuCache = (MenuCache) webApplicationContext.getBean("menuCache");
 }
  /**
   * @param storeValue
   * @param rootPath
   * @param context
   * @param nodeService
   * @param searchService
   * @param namespaceService
   * @param tenantService
   * @param m_transactionService
   */
  private void initializeRootNode(
      String storeValue,
      String rootPath,
      WebApplicationContext context,
      NodeService nodeService,
      SearchService searchService,
      NamespaceService namespaceService,
      TenantService tenantService,
      TransactionService m_transactionService) {

    // Use the system user as the authenticated context for the filesystem initialization

    AuthenticationContext authComponent =
        (AuthenticationContext) context.getBean("authenticationContext");
    authComponent.setSystemUserAsCurrentUser();

    // Wrap the initialization in a transaction

    UserTransaction tx = m_transactionService.getUserTransaction(true);

    try {
      // Start the transaction

      if (tx != null) tx.begin();

      StoreRef storeRef = new StoreRef(storeValue);

      if (nodeService.exists(storeRef) == false) {
        throw new RuntimeException("No store for path: " + storeRef);
      }

      NodeRef storeRootNodeRef = nodeService.getRootNode(storeRef);

      List<NodeRef> nodeRefs =
          searchService.selectNodes(storeRootNodeRef, rootPath, null, namespaceService, false);

      if (nodeRefs.size() > 1) {
        throw new RuntimeException(
            "Multiple possible children for : \n"
                + "   path: "
                + rootPath
                + "\n"
                + "   results: "
                + nodeRefs);
      } else if (nodeRefs.size() == 0) {
        throw new RuntimeException("Node is not found for : \n" + "   root path: " + rootPath);
      }

      defaultRootNode = nodeRefs.get(0);

      // Commit the transaction
      if (tx != null) tx.commit();
    } catch (Exception ex) {
      logger.error(ex);
    } finally {
      // Clear the current system user

      authComponent.clearCurrentSecurityContext();
    }
  }
Пример #24
0
    /*
     * 创建事件 业务部分写在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;
    }
 private <T> T getBeanByName(String name, Class<T> requiredType, Class<? extends T> defaultType) {
   try {
     return applicationContext.getBean(name, requiredType);
   } catch (NoSuchBeanDefinitionException ex) {
     return (defaultType != null) ? BeanUtils.instantiate(defaultType) : null;
   }
 }
Пример #26
0
  @RequestMapping(value = "/userBooking", method = RequestMethod.GET)
  public String bookingCart(Model model, HttpSession session) {
    if (!SessionUtils.isUser(session)) {
      return "index";
    }
    UserDAO userDAO = (UserDAO) context.getBean("userDAO");
    User user = userDAO.get(SessionUtils.getUserIdFromSessionOrNull(session));
    CartDAO cartDAO = (CartDAO) context.getBean("cartDAO");
    Cart cart = cartDAO.getUserCart(user);

    ArrayList<CartBooking> bookings = createBookingsToDisplay(cart);
    model.addAttribute("bookings", bookings);
    model.addAttribute("user", user);

    return "userBooking";
  }
Пример #27
0
 public void setServlet(ActionServlet actionServlet) {
   super.setServlet(actionServlet);
   ServletContext servletContext = actionServlet.getServletContext();
   WebApplicationContext wac =
       WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
   this.petStore = (PetStoreFacade) wac.getBean("petStore");
 }
Пример #28
0
  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());
  }
Пример #29
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");
  }
Пример #30
0
 public void init(ServletConfig config) throws ServletException {
   ServletContext servletContext = config.getServletContext();
   this.wac = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
   this.customerMgm = (CustomerMgm) this.wac.getBean("customerMgmImpl");
   baseDao = (BaseDAO) wac.getBean("systemDao");
   servletConfig = config;
 }