@Override
  public ReportDesign getReportDesign() {
    ReportDesign design = new ReportDesign();
    design.setName("MOH 361A Register Design");
    design.setReportDefinition(this.getReportDefinition());
    design.setRendererType(ExcelTemplateRenderer.class);

    Properties props = new Properties();
    props.put("repeatingSections", "sheet:2,row:4,dataset:allPatients");

    design.setProperties(props);

    ReportDesignResource resource = new ReportDesignResource();
    resource.setName("template.xls");
    InputStream is =
        OpenmrsClassLoader.getInstance()
            .getResourceAsStream("templates/MOH361AReportTemplate_0_2.xls");

    if (is == null) throw new APIException("Could not find report template.");

    try {
      resource.setContents(IOUtils.toByteArray(is));
    } catch (IOException ex) {
      throw new APIException("Could not create report design for MOH 361A Register.", ex);
    }

    IOUtils.closeQuietly(is);
    design.addResource(resource);

    return design;
  }
  /**
   * This method is called for every request for a page/image/javascript file/etc The main point of
   * this is to make sure the user's current userContext is on the session and on the current thread
   *
   * @see
   *     org.springframework.web.filter.OncePerRequestFilter#doFilterInternal(javax.servlet.http.HttpServletRequest,
   *     javax.servlet.http.HttpServletResponse, javax.servlet.FilterChain)
   */
  @Override
  protected void doFilterInternal(
      HttpServletRequest httpRequest, HttpServletResponse httpResponse, FilterChain chain)
      throws ServletException, IOException {

    HttpSession httpSession = httpRequest.getSession();

    // used by htmlInclude tag
    httpRequest.setAttribute(
        WebConstants.INIT_REQ_UNIQUE_ID, String.valueOf(System.currentTimeMillis()));

    if (log.isDebugEnabled()) {
      log.debug("requestURI " + httpRequest.getRequestURI());
      log.debug("requestURL " + httpRequest.getRequestURL());
      log.debug("request path info " + httpRequest.getPathInfo());
    }

    // User context is created if it doesn't already exist and added to the session
    // note: this usercontext storage logic is copied to webinf/view/uncaughtexception.jsp to
    // 		 prevent stack traces being shown to non-authenticated users
    UserContext userContext =
        (UserContext) httpSession.getAttribute(WebConstants.OPENMRS_USER_CONTEXT_HTTPSESSION_ATTR);

    // default the session username attribute to anonymous
    httpSession.setAttribute("username", "-anonymous user-");

    // if there isn't a userContext on the session yet, create one
    // and set it onto the session
    if (userContext == null) {
      userContext = new UserContext();
      httpSession.setAttribute(WebConstants.OPENMRS_USER_CONTEXT_HTTPSESSION_ATTR, userContext);

      if (log.isDebugEnabled())
        log.debug("Just set user context " + userContext + " as attribute on session");
    } else {
      // set username as attribute on session so parent servlet container
      // can identify sessions easier
      User user = userContext.getAuthenticatedUser();
      if (user != null) httpSession.setAttribute("username", user.getUsername());
    }

    // set the locale on the session (for the servlet container as well)
    httpSession.setAttribute("locale", userContext.getLocale());

    // Add the user context to the current thread
    Context.setUserContext(userContext);
    Thread.currentThread().setContextClassLoader(OpenmrsClassLoader.getInstance());

    log.debug("before chain.Filter");

    // continue the filter chain (going on to spring, authorization, etc)
    try {
      chain.doFilter(httpRequest, httpResponse);
    } finally {
      Context.clearUserContext();
    }

    log.debug("after chain.doFilter");
  }
  /** Delete an existing AutoGeneration Option */
  @RequestMapping("/module/idgen/deleteAutoGenerationOption")
  public ModelAndView deleteAutoGenerationOption(
      ModelMap model,
      HttpServletRequest request,
      @RequestParam("autoGenerationOption") AutoGenerationOption option) {
    if (Context.isAuthenticated()) {
      Thread.currentThread().setContextClassLoader(OpenmrsClassLoader.getInstance());
      Context.getService(IdentifierSourceService.class).purgeAutoGenerationOption(option);
    }

    // just display the edit page again
    return new ModelAndView("redirect:/module/idgen/manageAutoGenerationOptions.form");
  }
 /** @see com.thoughtworks.xstream.mapper.Mapper#serializedClass(java.lang.Class) */
 @SuppressWarnings("unchecked")
 public String serializedClass(Class type) {
   String classNameWithoutEnhanced = removeSignature(super.serializedClass(type));
   Class actualClass = null;
   try {
     // here re-get the actual class in order to put the alias name of the acutal class(which is
     // delegated by cglib proxy) into xml string
     actualClass = OpenmrsClassLoader.getInstance().loadClass(classNameWithoutEnhanced);
   } catch (ClassNotFoundException e) {
     return classNameWithoutEnhanced;
   }
   // here assure xstream can get the alias name of the actual class which is proxied by cglib
   return super.serializedClass(actualClass);
 }
  /** @see org.openmrs.api.EncounterService#getActiveEncounterVisitHandler() */
  @Override
  @Transactional(readOnly = true)
  public EncounterVisitHandler getActiveEncounterVisitHandler() throws APIException {

    String handlerGlobalValue =
        Context.getAdministrationService()
            .getGlobalProperty(OpenmrsConstants.GP_VISIT_ASSIGNMENT_HANDLER, null);

    if (StringUtils.isBlank(handlerGlobalValue)) {
      return null;
    }

    EncounterVisitHandler handler = null;

    // convention = [NamePrefix:beanName] or [className]
    String namePrefix = OpenmrsConstants.REGISTERED_COMPONENT_NAME_PREFIX;

    if (handlerGlobalValue.startsWith(namePrefix)) {
      String beanName = handlerGlobalValue.substring(namePrefix.length());

      handler = Context.getRegisteredComponent(beanName, EncounterVisitHandler.class);
    } else {
      Object instance;

      try {
        instance = OpenmrsClassLoader.getInstance().loadClass(handlerGlobalValue).newInstance();
      } catch (Exception ex) {
        throw new APIException(
            "Failed to instantiate assignment handler object for class class: "
                + handlerGlobalValue,
            ex);
      }

      if (instance instanceof EncounterVisitHandler) {
        handler = (EncounterVisitHandler) instance;
      } else {
        throw new APIException(
            "The registered visit assignment handler should implement the EncounterVisitHandler interface");
      }
    }

    return handler;
  }
  protected void populateModel(HttpServletRequest request, Map<String, Object> model) {

    // TODO: Figure out why this is necessary.
    Thread.currentThread().setContextClassLoader(OpenmrsClassLoader.getInstance());
    model.put("portletUUID", UUID.randomUUID().toString().replace("-", ""));

    // Get the uuid of the reportDesign, if supplied
    ReportService rs = Context.getService(ReportService.class);
    String processorUuid = (String) model.get("processorUuid");
    ReportProcessorConfiguration reportProcessorConfiguration = new ReportProcessorConfiguration();
    if (StringUtils.isNotEmpty(processorUuid)) {
      reportProcessorConfiguration = rs.getReportProcessorConfigurationByUuid(processorUuid);
    }
    model.put("reportProcessorConfiguration", reportProcessorConfiguration);

    List<Class<? extends ReportProcessor>> processorTypes =
        new ArrayList<Class<? extends ReportProcessor>>();
    for (ReportProcessor p : Context.getRegisteredComponents(ReportProcessor.class)) {
      processorTypes.add(p.getClass());
    }
    model.put("reportProcessorTypes", processorTypes);
    model.put("reportDesigns", rs.getAllReportDesigns(false));
  }
  /** Edit a new or existing AutoGeneration Option */
  @RequestMapping("/module/idgen/editAutoGenerationOption")
  public void editAutoGenerationOption(
      ModelMap model,
      HttpServletRequest request,
      @RequestParam(required = false, value = "autoGenerationOption")
          AutoGenerationOption option, // expects to get either an option or an identifier type
      @RequestParam(required = false, value = "identifierType") PatientIdentifierType type) {

    if (Context.isAuthenticated()) {
      Thread.currentThread().setContextClassLoader(OpenmrsClassLoader.getInstance());

      IdentifierSourceService iss = Context.getService(IdentifierSourceService.class);
      LocationService locationService = Context.getLocationService();

      if (option == null) {
        option = new AutoGenerationOption(type);
      }

      model.addAttribute("option", option);
      model.addAttribute(
          "availableSources", iss.getIdentifierSourcesByType(true).get(option.getIdentifierType()));
      model.addAttribute("availableLocations", locationService.getAllLocations());
    }
  }
  /**
   * Refreshes the given application context "properly" in OpenMRS. Will first shut down the Context
   * and destroy the classloader, then will refresh and set everything back up again.
   *
   * @param ctx Spring application context that needs refreshing.
   * @param isOpenmrsStartup if this refresh is being done at application startup.
   * @param startedModule the module that was just started and waiting on the context refresh.
   * @return AbstractRefreshableApplicationContext The newly refreshed application context.
   */
  public static AbstractRefreshableApplicationContext refreshApplicationContext(
      AbstractRefreshableApplicationContext ctx, boolean isOpenmrsStartup, Module startedModule) {
    // notify all started modules that we are about to refresh the context
    for (Module module : ModuleFactory.getStartedModules()) {
      try {
        if (module.getModuleActivator() != null) module.getModuleActivator().willRefreshContext();
      } catch (Throwable t) {
        log.warn("Unable to call willRefreshContext() method in the module's activator", t);
      }
    }

    OpenmrsClassLoader.saveState();
    ServiceContext.destroyInstance();

    try {
      ctx.stop();
      ctx.close();
    } catch (Exception e) {
      log.warn("Exception while stopping and closing context: ", e);
      // Spring seems to be trying to refresh the context instead of /just/ stopping
      // pass
    }
    OpenmrsClassLoader.destroyInstance();
    ctx.setClassLoader(OpenmrsClassLoader.getInstance());
    Thread.currentThread().setContextClassLoader(OpenmrsClassLoader.getInstance());

    ServiceContext.getInstance().startRefreshingContext();
    try {
      ctx.refresh();
    } finally {
      ServiceContext.getInstance().doneRefreshingContext();
    }

    ctx.setClassLoader(OpenmrsClassLoader.getInstance());
    Thread.currentThread().setContextClassLoader(OpenmrsClassLoader.getInstance());

    OpenmrsClassLoader.restoreState();

    OpenmrsClassLoader.setThreadsToNewClassLoader();

    // reload the advice points that were lost when refreshing Spring
    if (log.isDebugEnabled())
      log.debug(
          "Reloading advice for all started modules: " + ModuleFactory.getStartedModules().size());

    try {
      // The call backs in this block may need lazy loading of objects
      // which will fail because we use an OpenSessionInViewFilter whose opened session
      // was closed when the application context was refreshed as above.
      // So we need to open another session now. TRUNK-3739
      Context.openSessionWithCurrentUser();

      for (Module module : ModuleFactory.getStartedModules()) {
        ModuleFactory.loadAdvice(module);
        try {
          ModuleFactory.passDaemonToken(module);

          if (module.getModuleActivator() != null) {
            module.getModuleActivator().contextRefreshed();
            try {
              // if it is system start up, call the started method for all started modules
              if (isOpenmrsStartup) module.getModuleActivator().started();
              // if refreshing the context after a user started or uploaded a new module
              else if (!isOpenmrsStartup && module.equals(startedModule))
                module.getModuleActivator().started();
            } catch (Exception e) {
              log.warn("Unable to invoke started() method on the module's activator", e);
              ModuleFactory.stopModule(module);
            }
          }

        } catch (Throwable t) {
          log.warn("Unable to invoke method on the module's activator ", t);
        }
      }
    } finally {
      Context.closeSessionWithCurrentUser();
    }

    return ctx;
  }