예제 #1
0
 /**
  * Utility method that allows tests to easily configure and save a global property
  *
  * @param string the name of the property to save
  * @param value the value of the property to save
  */
 public static void saveGlobalProperty(String name, String value) {
   GlobalProperty gp = Context.getAdministrationService().getGlobalPropertyObject(name);
   if (gp == null) {
     gp = new GlobalProperty(name);
   }
   gp.setPropertyValue(value);
   Context.getAdministrationService().saveGlobalProperty(gp);
 }
 @Before
 public void setup() throws Exception {
   GlobalProperty gp =
       Context.getAdministrationService()
           .getGlobalPropertyObject(WebConstants.GP_ALLOWED_LOGIN_ATTEMPTS_PER_IP);
   if (gp == null) {
     gp = new GlobalProperty();
     gp.setProperty(WebConstants.GP_ALLOWED_LOGIN_ATTEMPTS_PER_IP);
   }
   gp.setPropertyValue("10");
   Context.getAdministrationService().saveGlobalProperty(gp);
 }
  public void get(PageModel model) {

    AdministrationService administrationService = Context.getAdministrationService();
    List<GlobalProperty> globalProps = administrationService.getAllGlobalProperties();
    // TODO Remove module global properties
    model.addAttribute("globalProperties", globalProps);
  }
예제 #4
0
  /**
   * Gets the default locale specified as a global property.
   *
   * @return default locale object.
   * @since 1.5
   * @should not return null if global property does not exist
   * @should not fail with empty global property value
   * @should not fail with bogus global property value
   * @should return locale object for global property
   * @should not cache locale when session is not open
   */
  public static Locale getDefaultLocale() {
    if (defaultLocaleCache == null) {
      if (Context.isSessionOpen()) {
        try {
          String locale =
              Context.getAdministrationService()
                  .getGlobalProperty(OpenmrsConstants.GLOBAL_PROPERTY_DEFAULT_LOCALE);

          if (StringUtils.hasLength(locale)) {
            try {
              defaultLocaleCache = fromSpecification(locale);
            } catch (Exception t) {
              log.warn("Unable to parse default locale global property value: " + locale, t);
            }
          }
        } catch (Exception e) {
          // swallow most of the stack trace for most users
          log.warn("Unable to get locale global property value. " + e.getMessage());
          log.trace("Unable to get locale global property value", e);
        }

        // if we weren't able to load the locale from the global property,
        // use the default one
        if (defaultLocaleCache == null)
          defaultLocaleCache =
              fromSpecification(OpenmrsConstants.GLOBAL_PROPERTY_DEFAULT_LOCALE_DEFAULT_VALUE);
      } else {
        // if session is not open, return the default locale without caching
        return fromSpecification(OpenmrsConstants.GLOBAL_PROPERTY_DEFAULT_LOCALE_DEFAULT_VALUE);
      }
    }

    return defaultLocaleCache;
  }
  /** @see {@link ExistingOrNewVisitAssignmentHandler#beforeCreateEncounter(Encounter)} */
  @Test
  @Verifies(
      value = "should resolve encounter and visit type uuids as global property values",
      method = "beforeCreateEncounter(Encounter)")
  public void beforeCreateEncounter_shouldResolveEncounterAndVisitTypeUuidsAsGlobalPropertyValues()
      throws Exception {
    final String encounterTypeUuid = "759799ab-c9a5-435e-b671-77773ada74e4";
    final String visitTypeUuid = "c0c579b0-8e59-401d-8a4a-976a0b183519";
    Encounter encounter = Context.getEncounterService().getEncounter(1);
    Assert.assertNull(encounter.getVisit());
    Assert.assertEquals(encounterTypeUuid, encounter.getEncounterType().getUuid());

    Calendar calendar = Calendar.getInstance();
    calendar.setTime(encounter.getEncounterDatetime());
    calendar.set(Calendar.YEAR, 1900);

    encounter.setEncounterDatetime(calendar.getTime());

    GlobalProperty gp =
        new GlobalProperty(
            OpenmrsConstants.GP_ENCOUNTER_TYPE_TO_VISIT_TYPE_MAPPING,
            encounterTypeUuid + ":" + visitTypeUuid);
    Context.getAdministrationService().saveGlobalProperty(gp);

    new ExistingOrNewVisitAssignmentHandler().beforeCreateEncounter(encounter);

    Assert.assertNotNull(encounter.getVisit());

    // should be set according toencounterTypeUuid:visitTypeUuid
    Assert.assertEquals(1, encounter.getEncounterType().getEncounterTypeId().intValue());
    Assert.assertEquals(
        Context.getVisitService().getVisitTypeByUuid(visitTypeUuid),
        encounter.getVisit().getVisitType());
  }
  /** @see {@link ExistingVisitAssignmentHandler#beforeCreateEncounter(Encounter)} */
  @Test
  @Verifies(
      value = "should assign mapping global property visit type",
      method = "beforeCreateEncounter(Encounter)")
  public void beforeCreateEncounter_shouldAssignMappingGlobalPropertyVisitType() throws Exception {
    Encounter encounter = Context.getEncounterService().getEncounter(1);
    Assert.assertNull(encounter.getVisit());

    Calendar calendar = Calendar.getInstance();
    calendar.setTime(encounter.getEncounterDatetime());
    calendar.set(Calendar.YEAR, 1900);

    encounter.setEncounterDatetime(calendar.getTime());

    GlobalProperty gp =
        new GlobalProperty(
            OpenmrsConstants.GP_ENCOUNTER_TYPE_TO_VISIT_TYPE_MAPPING, "3:4, 5:2, 1:2, 2:2");
    Context.getAdministrationService().saveGlobalProperty(gp);

    new ExistingOrNewVisitAssignmentHandler().beforeCreateEncounter(encounter);

    Assert.assertNotNull(encounter.getVisit());

    // should be set according to: 1:2 encounterTypeId:visitTypeId
    Assert.assertEquals(1, encounter.getEncounterType().getEncounterTypeId().intValue());
    Assert.assertEquals(
        Context.getVisitService().getVisitType(2), encounter.getVisit().getVisitType());
  }
 /**
  * gets globalProperty value by giving globalProperty Key
  *
  * @param propertyName
  * @return propertyValue
  */
 public int getGlobalProperty(String propertyName) {
   AdministrationService administrationService = Context.getAdministrationService();
   int propertyValue = 0;
   if (propertyName != null && !propertyName.equals(""))
     propertyValue = Integer.parseInt(administrationService.getGlobalProperty(propertyName));
   return propertyValue;
 }
  /**
   * Refresh the local cache of Flags by loading all enabled Flags from the database Also refresh
   * the privilege cache Note that flags and tags must be eagerly loaded for this to work
   */
  private void refreshCache() {
    // get the enabled flags and all tags for the flag and tag caches
    flagCache = dao.getAllEnabledFlags();
    tagCache = getAllTags();

    // alphabetize the flags, and sort by by priority ranking so that result sets are returned that
    // way
    Collections.sort(flagCache, new FlagAlphaComparator());
    Collections.sort(flagCache, new FlagPriorityComparator());

    // get the privileges associate with the patient flags default user for the privileges cache
    try {
      Context.addProxyPrivilege("View Users");
      String username =
          Context.getAdministrationService().getGlobalProperty("patientflags.username");
      User user = Context.getUserService().getUserByUsername(username);

      if (user != null) {
        if (user.isSuperUser()) { // need to explicitly get all privileges if user is a super user
          privilegeCache = Context.getUserService().getAllPrivileges();
        } else {
          privilegeCache = user.getPrivileges();
        }
      } else {
        privilegeCache = null;
      }
    } finally {
      Context.removeProxyPrivilege("View Users");
    }

    // set the initialized flag to true
    isInitialized = true;
  }
  /** @see org.openmrs.module.patientflags.api.FlagService#getPatientFlagsProperties() */
  public PatientFlagsProperties getPatientFlagsProperties() {
    PatientFlagsProperties properties = new PatientFlagsProperties();

    // initialize Patient Flags Properties based on values in global_properties
    String patientHeaderDisplay =
        Context.getAdministrationService().getGlobalProperty("patientflags.patientHeaderDisplay");
    if (patientHeaderDisplay == null) {
      properties.setPatientHeaderDisplay(null);
      log.error(
          "Unable to initialize patientHeaderDisplay parameter, invalid or missing value in global_properties table.");
    } else if (patientHeaderDisplay.equals("true")) {
      properties.setPatientHeaderDisplay(true);
    } else if (patientHeaderDisplay.equals("false")) {
      properties.setPatientHeaderDisplay(false);
    } else {
      properties.setPatientHeaderDisplay(null);
      log.error(
          "Unable to initialize patientHeaderDisplay parameter, invalid or missing value in global_properties table.");
    }

    String patientOverviewDisplay =
        Context.getAdministrationService().getGlobalProperty("patientflags.patientOverviewDisplay");
    if (patientOverviewDisplay == null) {
      properties.setPatientOverviewDisplay(null);
      log.error(
          "Unable to initialize patientOverviewDisplay parameter, invalid or missing value in global_properties table.");
    } else if (patientOverviewDisplay.equals("true")) {
      properties.setPatientOverviewDisplay(true);
    } else if (patientOverviewDisplay.equals("false")) {
      properties.setPatientOverviewDisplay(false);
    } else {
      properties.setPatientOverviewDisplay(null);
      log.error(
          "Unable to initialize patientOverviewDisplay parameter, invalid or missing value in global_properties table.");
    }

    String username = Context.getAdministrationService().getGlobalProperty("patientflags.username");
    if (username == null) {
      properties.setUsername(null);
      log.error(
          "Unable to initialize username parameter, invalid or missing value in global_properties table.");
    } else {
      properties.setUsername(username);
    }

    return properties;
  }
  /**
   * Called for GET requests only on the databaseChangesInfo page. POST page requests are invalid
   * and ignored.
   *
   * @param model the key value pair that will be accessible from the jsp page
   * @throws Exception if there is trouble getting the database changes from liquibase
   */
  @RequestMapping(method = RequestMethod.GET, value = "/admin/maintenance/localesAndThemes")
  public void showPage(ModelMap model) throws Exception {
    String theme =
        Context.getAdministrationService()
            .getGlobalProperty(OpenmrsConstants.GLOBAL_PROPERTY_DEFAULT_THEME);
    model.addAttribute("theme", theme);

    String locale =
        Context.getAdministrationService()
            .getGlobalProperty(OpenmrsConstants.GLOBAL_PROPERTY_DEFAULT_LOCALE);
    model.addAttribute("locale", locale);

    String allowedLocales =
        Context.getAdministrationService()
            .getGlobalProperty(OpenmrsConstants.GLOBAL_PROPERTY_LOCALE_ALLOWED_LIST);
    model.addAttribute("allowedLocales", allowedLocales);
  }
 public static Date fromSubmitString2Date(String date) throws ParseException {
   SimpleDateFormat dateFormat =
       new SimpleDateFormat(
           Context.getAdministrationService()
               .getGlobalProperty(
                   AMRSComplexObsConstants.GLOBAL_PROP_KEY_DATE_SUBMIT_FORMAT,
                   AMRSComplexObsConstants.DEFAULT_DATE_SUBMIT_FORMAT));
   return dateFormat.parse(date);
 }
  public void afterReturning(Object returnValue, Method method, Object[] args, Object target)
      throws Throwable {
    log.debug("Intercepted an Encounter Save");
    if (method.getName().equals("saveEncounter")) {
      User autheticatedUser = Context.getAuthenticatedUser();

      if (autheticatedUser != null) {
        Collection<Role> userRoles = autheticatedUser.getAllRoles();

        if (userRoles != null && userRoles.size() > 0) {
          String prop =
              Context.getAdministrationService()
                  .getGlobalProperty(OncologyPOCConstants.GP_INTERCEPTROLES);

          if (prop != null) {
            String[] interceptRoles = prop.split(",");
            boolean interceptThisOne = false;
            Role interceptedRole = null;

            for (String role : interceptRoles) {
              for (Role userRole : userRoles) {
                if (role.equalsIgnoreCase(userRole.getRole())) {
                  interceptThisOne = true;
                  interceptedRole = userRole;
                  break;
                }
              }
              if (interceptThisOne) break;
            }

            if (interceptThisOne) {
              Encounter encounter = (Encounter) returnValue;
              if (encounter != null
                  && encounter.getPatient() != null
                  && encounter.getForm() != null) {
                OncologyPOCService service =
                    (OncologyPOCService) Context.getService(OncologyPOCService.class);
                SubEncounter subEncounter = service.getSubEncounter(encounter.getEncounterId());

                if (interceptedRole.hasPrivilege(OncologyPOCConstants.PRIV_CLINICIAN)) {
                  log.debug("Deleting subEncounter");
                  service.deleteSubEncounter(subEncounter);
                } else {
                  log.debug("Saving subEncounter");
                  if (subEncounter == null) {
                    subEncounter = new SubEncounter();
                    subEncounter.setEncounterId(encounter.getEncounterId());
                  }
                  service.saveSubEncounter(subEncounter);
                }
              }
            }
          }
        }
      }
    }
  }
 /** @see org.openmrs.api.EncounterService#checkIfEncounterTypesAreLocked() */
 @Transactional(readOnly = true)
 public void checkIfEncounterTypesAreLocked() {
   String locked =
       Context.getAdministrationService()
           .getGlobalProperty(OpenmrsConstants.GLOBAL_PROPERTY_ENCOUNTER_TYPES_LOCKED, "false");
   if (locked.toLowerCase().equals("true")) {
     throw new EncounterTypeLockedException();
   }
 }
  protected void populateModel(HttpServletRequest request, Map<String, Object> model) {
    // TODO: this only cached the first name or address template that comes through. I need to cache
    // one of each.
    String templateName = (String) model.get("layoutTemplateName");
    String thisLayoutName = getDefaultDivId() + "." + templateName;
    if (!thisLayoutName.equals(model.get("cachedLayoutName"))) {
      LayoutSupport layoutSupport = getLayoutSupportInstance();
      LayoutTemplate layoutTemplate = layoutSupport.getDefaultLayoutTemplate();

      if (layoutTemplate == null) {
        log.debug("Could not get default LayoutTemplate from " + layoutSupport.getClass());
      }

      if (templateName != null) {
        if (layoutSupport.getLayoutTemplateByName(templateName) != null) {
          layoutTemplate = layoutSupport.getLayoutTemplateByName(templateName);
        } else {
          log.debug("unable to get template by the name of " + templateName + ", using default");
        }
      }

      // Check global properties for defaults/overrides in the form of n=v,n1=v1, etc
      String customDefaults =
          Context.getAdministrationService().getGlobalProperty("layout.address.defaults");
      if (customDefaults != null) {
        String[] tokens = customDefaults.split(",");
        Map<String, String> elementDefaults = layoutTemplate.getElementDefaults();

        for (String token : tokens) {
          String[] pair = token.split("=");
          if (pair.length == 2) {
            String name = pair[0];
            String val = pair[1];

            if (elementDefaults == null) {
              elementDefaults = new HashMap<String, String>();
            }
            elementDefaults.put(name, val);
          } else {
            log.debug("Found invalid token while parsing GlobalProperty address format defaults");
          }
        }

        layoutTemplate.setElementDefaults(elementDefaults);
      }

      String divName = (String) model.get("portletDivId");
      if (divName == null) {
        model.put("portletDivId", getDefaultDivId());
      }

      model.put("layoutTemplate", layoutTemplate);
      model.put("layoutTemplateName", templateName);
      model.put("cachedLayoutName", thisLayoutName);
    }
  }
  /**
   * Called upon save of the page
   *
   * @param theme the theme name to save
   * @param locale the locale to save (en, en_GB, es, etc)
   * @throws Exception
   */
  @RequestMapping(method = RequestMethod.POST, value = "/admin/maintenance/localesAndThemes")
  public String saveDefaults(
      @RequestParam("theme") String theme, @RequestParam("locale") String locale) throws Exception {

    // save the theme
    GlobalProperty themeGP =
        Context.getAdministrationService()
            .getGlobalPropertyObject(OpenmrsConstants.GLOBAL_PROPERTY_DEFAULT_THEME);
    themeGP.setPropertyValue(theme);
    Context.getAdministrationService().saveGlobalProperty(themeGP);

    // save the locale
    GlobalProperty localeGP =
        Context.getAdministrationService()
            .getGlobalPropertyObject(OpenmrsConstants.GLOBAL_PROPERTY_DEFAULT_LOCALE);
    localeGP.setPropertyValue(locale);
    Context.getAdministrationService().saveGlobalProperty(localeGP);

    return "redirect:/admin/maintenance/localesAndThemes.form";
  }
예제 #16
0
 /** @see {@link LocaleUtility#getLocalesInOrder()} */
 @Test
 @Verifies(
     value = "should return a set of locales with no duplicates",
     method = "getLocalesInOrder()")
 public void getLocalesInOrder_shouldReturnASetOfLocalesWithNoDuplicates() throws Exception {
   GlobalProperty gp =
       new GlobalProperty(
           OpenmrsConstants.GLOBAL_PROPERTY_LOCALE_ALLOWED_LIST,
           "lu_UG, lu, sw_KE, en_US, en, en, sw_KE",
           "Test Allowed list of locales");
   Context.getAdministrationService().saveGlobalProperty(gp);
   GlobalProperty defaultLocale =
       new GlobalProperty(
           OpenmrsConstants.GLOBAL_PROPERTY_DEFAULT_LOCALE, "lu", "Test Allowed list of locales");
   Context.getAdministrationService().saveGlobalProperty(defaultLocale);
   Locale lu_UG = new Locale("lu", "UG");
   Context.setLocale(lu_UG);
   // note that unique list of locales should be lu_UG, lu, sw_KE, en_US, en
   Assert.assertEquals(6, LocaleUtility.getLocalesInOrder().size());
 }
예제 #17
0
  /**
   * This test doesn't really test anything, and it should ALWAYS be the last method in this class.
   * <br>
   * <br>
   * This method just resets the current user's locale so that when things are run in batches all
   * tests still work.
   */
  @Test
  public void should_resetTheLocale() {
    // set user locale to nothing
    Context.setLocale(null);

    // clear out the caches
    GlobalProperty defaultLocale =
        new GlobalProperty(
            OpenmrsConstants.GLOBAL_PROPERTY_DEFAULT_LOCALE, "", "blanking out default locale");
    Context.getAdministrationService().saveGlobalProperty(defaultLocale);
  }
예제 #18
0
  /** @see {@link LocaleUtility#getDefaultLocale()} */
  @Test
  @Verifies(
      value = "should not fail with empty global property value",
      method = "getDefaultLocale()")
  public void getDefaultLocale_shouldNotFailWithEmptyGlobalPropertyValue() throws Exception {
    Context.getAdministrationService()
        .saveGlobalProperty(
            new GlobalProperty(OpenmrsConstants.GLOBAL_PROPERTY_DEFAULT_LOCALE, ""));

    // check for nonnullness
    Assert.assertNotNull(LocaleUtility.getDefaultLocale());
  }
예제 #19
0
  /** @see {@link LocaleUtility#getDefaultLocale()} */
  @Test
  @Verifies(
      value = "should return locale object for global property",
      method = "getDefaultLocale()")
  public void getDefaultLocale_shouldReturnLocaleObjectForGlobalProperty() throws Exception {
    GlobalProperty gp =
        Context.getAdministrationService()
            .saveGlobalProperty(
                new GlobalProperty(OpenmrsConstants.GLOBAL_PROPERTY_DEFAULT_LOCALE, "ja"));

    Assert.assertEquals(Locale.JAPANESE, LocaleUtility.getDefaultLocale());
  }
 public static boolean isTimesheetRequired() {
   AdministrationService adminService = Context.getAdministrationService();
   boolean timesheetRequired;
   try {
     timesheetRequired =
         Boolean.parseBoolean(
             adminService.getGlobalProperty(CashierWebConstants.TIMESHEET_REQUIRED_PROPERTY));
   } catch (Exception e2) {
     timesheetRequired = false;
   }
   return timesheetRequired;
 }
  /**
   * @see
   *     org.openmrs.module.patientflags.api.FlagService#savePatientFlagsProperties(PatientFlagsProperties)
   */
  public void savePatientFlagsProperties(PatientFlagsProperties properties) {
    // save updated property values back to global_properties
    if (properties != null) {
      try {
        GlobalProperty patientHeaderDisplay =
            Context.getAdministrationService()
                .getGlobalPropertyObject("patientflags.patientHeaderDisplay");
        patientHeaderDisplay.setPropertyValue(properties.getPatientHeaderDisplay().toString());
        Context.getAdministrationService().saveGlobalProperty(patientHeaderDisplay);

        GlobalProperty patientOverviewDisplay =
            Context.getAdministrationService()
                .getGlobalPropertyObject("patientflags.patientOverviewDisplay");
        patientOverviewDisplay.setPropertyValue(properties.getPatientOverviewDisplay().toString());
        Context.getAdministrationService().saveGlobalProperty(patientOverviewDisplay);

        GlobalProperty username =
            Context.getAdministrationService().getGlobalPropertyObject("patientflags.username");
        username.setPropertyValue(properties.getUsername());
        Context.getAdministrationService().saveGlobalProperty(username);

        // refresh the cache so the privileges are updated if username changed
        refreshCache();
      } catch (Throwable t) {
        throw new APIException(
            "Unable to update Patient Flags global properties. Try restarting Patient Flags module.",
            t);
      }
    } else {
      log.error("Cannot save Patient Flags properties - invalid PatientFlagsProperties object");
    }
  }
예제 #22
0
  /** @see {@link LocaleUtility#getDefaultLocale()} */
  @Test
  @Verifies(
      value = "should not return null if global property does not exist",
      method = "getDefaultLocale()")
  public void getDefaultLocale_shouldNotReturnNullIfGlobalPropertyDoesNotExist() throws Exception {
    // sanity check
    Assert.assertNull(
        Context.getAdministrationService()
            .getGlobalProperty(OpenmrsConstants.GLOBAL_PROPERTY_DEFAULT_LOCALE));

    // check for nonnullness
    Assert.assertNotNull(LocaleUtility.getDefaultLocale());
  }
  @Before
  public void setupDatabase() throws Exception {
    executeDataSet(
        XML_DATASET_PATH + new TestUtil().getTestDatasetFilename(XML_REGRESSION_TEST_DATASET));
    executeDataSet(
        XML_DATASET_PATH + new TestUtil().getTestDatasetFilename(XML_DRUG_ORDER_ELEMENT_DATASET));

    String xml =
        (new TestUtil())
            .loadXmlFromFile(XML_DATASET_PATH + XML_HTML_FORM_ENTRY_REGIMEN_UTIL_TEST_DATASET);
    GlobalProperty gp = new GlobalProperty(OpenmrsConstants.GLOBAL_PROPERTY_STANDARD_DRUG_REGIMENS);
    gp.setPropertyValue(xml);
    Context.getAdministrationService().saveGlobalProperty(gp);
  }
  /**
   * This method will be used for remote registration. Registered patient information will be placed
   * into an xml file for the FormEntry processor.
   *
   * @param paramPatient
   * @param paramString1
   * @param paramString2
   * @throws APIException
   */
  public void registerPatient(Patient paramPatient, String paramString1, String paramString2)
      throws APIException {
    File localFile1 = OpenmrsUtil.getDirectoryInApplicationDataDirectory("amrsregistration");
    File localFile2 = new File(localFile1, "registrationTemplate.xml");
    try {
      String str1 = OpenmrsUtil.getFileAsString(localFile2);

      Properties localProperties = new Properties();
      localProperties.setProperty("resource.loader", "class");
      localProperties.setProperty(
          "class.resource.loader.description", "VelocityClasspathResourceLoader");
      localProperties.setProperty(
          "class.resource.loader.class",
          "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
      localProperties.setProperty(
          "runtime.log.logsystem.class", "org.apache.velocity.runtime.log.NullLogSystem");

      Velocity.init(localProperties);
      VelocityContext localVelocityContext = new VelocityContext();
      localVelocityContext.put("locale", Context.getLocale());
      localVelocityContext.put(
          "patient", Context.getPatientService().getPatient(paramPatient.getPatientId()));
      localVelocityContext.put("user", Context.getAuthenticatedUser());
      localVelocityContext.put("fn", new DataExportFunctions());
      localVelocityContext.put("dateEntered", new Date());
      localVelocityContext.put("sid", paramString1);
      localVelocityContext.put("uid", paramString2);
      StringWriter localStringWriter = new StringWriter();
      Velocity.evaluate(localVelocityContext, localStringWriter, super.getClass().getName(), str1);

      String str2 =
          Context.getAdministrationService().getGlobalProperty("remoteformentry.pending_queue_dir");
      File localFile3 = OpenmrsUtil.getDirectoryInApplicationDataDirectory(str2);
      Date localDate = new Date();
      String str3 = "amrsregistration_" + localDate.toString();
      File localFile4 = new File(localFile3, str3);
      try {
        FileWriter localFileWriter = new FileWriter(localFile4);
        localFileWriter.write(localStringWriter.toString());
        localFileWriter.flush();
        localFileWriter.close();
      } catch (IOException localIOException) {
        log.error("Unable to write amrsregistration output file.", localIOException);
      }
    } catch (Exception localException) {
      log.error("Unable to create amrsregistration output file", localException);
      throw new APIException(localException);
    }
  }
예제 #25
0
  /**
   * Utility method that returns a collection of all openmrs system locales, the set includes the
   * current logged in user's preferred locale if any is set, the default locale, allowed locales in
   * the order they are specified in the 'allowed.locale.list' global property and 'en' at the very
   * end of the set if it isn't yet among them.
   *
   * @returns a collection of all specified and allowed locales with no duplicates.
   * @should return a set of locales with a predictable order
   * @should return a set of locales with no duplicates
   * @should have default locale as the first element if user has no preferred locale
   * @should have default locale as the second element if user has a preferred locale
   * @should always have english included in the returned collection
   * @should always have default locale default value included in the returned collection
   * @since 1.7
   */
  public static Set<Locale> getLocalesInOrder() {

    Set<Locale> locales = new LinkedHashSet<Locale>();
    locales.add(Context.getLocale());
    locales.add(getDefaultLocale());
    if (localesAllowedListCache == null)
      localesAllowedListCache = Context.getAdministrationService().getAllowedLocales();

    if (localesAllowedListCache != null) locales.addAll(localesAllowedListCache);

    locales.add(Locale.ENGLISH);
    locales.add(fromSpecification(OpenmrsConstants.GLOBAL_PROPERTY_DEFAULT_LOCALE_DEFAULT_VALUE));

    return locales;
  }
예제 #26
0
  /**
   * Returns all modules that are marked as mandatory. Currently this means there is a
   * <moduleid>.mandatory=true global property.
   *
   * @return list of modules ids for mandatory modules
   * @should return mandatory module ids
   */
  public static List<String> getMandatoryModules() {

    List<String> mandatoryModuleIds = new ArrayList<String>();

    try {
      List<GlobalProperty> props =
          Context.getAdministrationService().getGlobalPropertiesBySuffix(".mandatory");

      for (GlobalProperty prop : props) {
        if ("true".equalsIgnoreCase(prop.getPropertyValue())) {
          mandatoryModuleIds.add(prop.getProperty().replace(".mandatory", ""));
        }
      }
    } catch (Throwable t) {
      log.warn("Unable to get the mandatory module list", t);
    }

    return mandatoryModuleIds;
  }
예제 #27
0
  /** @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;
  }
  /** Validate patient records */
  @AppAction(EmrConstants.APP_DEVELOPER)
  public List<SimpleObject> validatePatients(UiUtils ui) {
    List<SimpleObject> problems = new ArrayList<SimpleObject>();

    for (Patient patient : Context.getPatientService().getAllPatients()) {
      BindException errors = new BindException(patient, "");
      Context.getAdministrationService().validate(patient, errors);

      if (errors.hasErrors()) {
        SimpleObject problem = new SimpleObject();
        problem.put("patient", ui.simplifyObject(patient));
        problem.put("errors", uniqueErrorMessages(errors));
        problem.put("cause", errors.getCause());
        problems.add(problem);
      }
    }

    return problems;
  }
 /** @see org.openmrs.api.SerializationService#getDefaultSerializer() */
 @Transactional(readOnly = true)
 public OpenmrsSerializer getDefaultSerializer() {
   String prop =
       Context.getAdministrationService()
           .getGlobalProperty(OpenmrsConstants.GLOBAL_PROPERTY_DEFAULT_SERIALIZER);
   if (StringUtils.isNotEmpty(prop)) {
     try {
       Class<?> clazz = Context.loadClass(prop);
       if (clazz != null && OpenmrsSerializer.class.isAssignableFrom(clazz)) {
         return (OpenmrsSerializer) clazz.newInstance();
       }
     } catch (Exception e) {
       log.info(
           "Cannot create an instance of " + prop + " - using builtin SimpleXStreamSerializer.");
     }
   } else {
     log.info("No default serializer specified - using builtin SimpleXStreamSerializer.");
   }
   return serializerMap.get(SimpleXStreamSerializer.class);
 }
예제 #30
0
  void submitProposedConcept(final ProposedConceptPackage conceptPackage) {

    checkNotNull(submissionRestTemplate);

    //
    // Could not figure out how to get Spring to send a basic authentication request using the
    // "proper" object approach
    // see: https://github.com/johnsyweb/openmrs-cpm/wiki/Gotchas
    //

    AdministrationService service = Context.getAdministrationService();
    SubmissionDto submission = submissionDtoFactory.create(conceptPackage);

    HttpHeaders headers =
        httpHeaderFactory.create(
            service.getGlobalProperty(CpmConstants.SETTINGS_USER_NAME_PROPERTY),
            service.getGlobalProperty(CpmConstants.SETTINGS_PASSWORD_PROPERTY));
    // headers = createHeaders(service.getGlobalProperty(CpmConstants.SETTINGS_USER_NAME_PROPERTY),
    //        service.getGlobalProperty(CpmConstants.SETTINGS_PASSWORD_PROPERTY));
    final HttpEntity requestEntity = new HttpEntity<SubmissionDto>(submission, headers);

    final String url =
        service.getGlobalProperty(CpmConstants.SETTINGS_URL_PROPERTY)
            + "/ws/cpm/dictionarymanager/proposals";
    ResponseEntity responseEntity =
        submissionRestTemplate.exchange(
            url, HttpMethod.POST, requestEntity, SubmissionResponseDto.class);

    //		final SubmissionResponseDto result =
    // submissionRestTemplate.postForObject("http://localhost:8080/openmrs/ws/cpm/dictionarymanager/proposals", submission, SubmissionResponseDto.class);
    //
    //        TODO: Find out how to determine success/failure for the submission returned by
    // dictionarymanagercontroller
    if (responseEntity == null || !responseEntity.getStatusCode().equals(HttpStatus.SC_OK)) {
      //            throw new ConceptProposalSubmissionException("Error in submitting proposed
      // concept");
      log.error("REsponseEntity status code is " + responseEntity.getStatusCode());
    }
    conceptPackage.setStatus(PackageStatus.SUBMITTED);
    Context.getService(ProposedConceptService.class).saveProposedConceptPackage(conceptPackage);
  }