public void get(
      @RequestParam(value = "definition", required = false) String uuid,
      @RequestParam(value = "definitionClass", required = false) String definitionClass,
      @SpringBean AdHocExportManager adHocExportManager,
      PageModel model)
      throws Exception {

    RowPerObjectDataSetDefinition definition = null;
    String initialStateJson = null;
    if (StringUtils.isNotBlank(uuid)) {
      definition = adHocExportManager.getAdHocDataSetByUuid(uuid);

      AdHocDataSet ds = new AdHocDataSet(definition);

      ObjectMapper jackson = new ObjectMapper();
      initialStateJson = jackson.writeValueAsString(ds);

    } else if (StringUtils.isNotBlank(definitionClass)) {
      Class<?> clazz = Context.loadClass(definitionClass);
      definition = (RowPerObjectDataSetDefinition) clazz.newInstance();
      definition.setUuid(null);
    } else {
      throw new IllegalArgumentException("definition or definitionClass is required");
    }
    model.addAttribute("definition", definition);
    model.addAttribute("initialStateJson", initialStateJson);
  }
  public Object fromString(Class clazz, String s) {
    Object o = null;
    try {
      o = Context.loadClass(s);
    } catch (ClassNotFoundException ex) {
    }

    return o;
  }
  @RequestMapping("/module/htmlformentry/drugSearch")
  public void localizedMessage(@RequestParam("term") String query, HttpServletResponse response)
      throws IOException {

    List<Drug> drugs;

    // we want to use a later API method from 1.8+ if it is available, so we need to access it via
    // reflection
    if (OpenmrsConstants.OPENMRS_VERSION_SHORT.startsWith("1.6")
        || OpenmrsConstants.OPENMRS_VERSION_SHORT.startsWith("1.7")) {
      drugs =
          conceptService.getDrugs(query); // this method returns retired drugs, so it is not ideal
    } else {
      try {
        Object conceptService =
            Context.getService(Context.loadClass("org.openmrs.api.ConceptService"));
        Method getDrugsMethod =
            conceptService
                .getClass()
                .getMethod(
                    "getDrugs",
                    String.class,
                    Concept.class,
                    boolean.class,
                    boolean.class,
                    boolean.class,
                    Integer.class,
                    Integer.class);

        drugs =
            (List<Drug>)
                getDrugsMethod.invoke(
                    conceptService,
                    query,
                    null,
                    true,
                    false,
                    false,
                    0,
                    100); // this method excludes retired drugs

      } catch (Exception ex) {
        throw new RuntimeException(
            "Unable to access ConceptService getDrugs method via reflection", ex);
      }
    }

    List<Map<String, Object>> simplified = drugCompatibility.simplify(drugs);

    response.setContentType("application/json");
    response.setCharacterEncoding("UTF-8");
    PrintWriter out = response.getWriter();

    new ObjectMapper().writeValue(out, simplified);
  }
 /** @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);
 }
 /** @see SerializedObjectDAO#convertSerializedObject(Class, SerializedObject) */
 @SuppressWarnings("unchecked")
 public <T extends OpenmrsObject> T convertSerializedObject(
     Class<T> clazz, SerializedObject serializedObject) throws DAOException {
   if (serializedObject == null) {
     return null;
   }
   OpenmrsSerializer serializer = getSerializer(serializedObject);
   T obj = null;
   try {
     Class<?> subtype = Context.loadClass(serializedObject.getSubtype());
     obj = (T) serializer.deserialize(serializedObject.getSerializedData(), subtype);
   } catch (Exception e) {
     // Do nothing here. Handled by null check below
   }
   if (obj == null) {
     throw new DAOException("Unable to deserialize object: " + serializedObject);
   }
   obj.setId(serializedObject.getId());
   obj.setUuid(serializedObject.getUuid());
   return obj;
 }
 /**
  * This method exists to allow us to quickly support providers as introduce in OpenMRS 1.9.x,
  * without having to branch the module. We should remove this method when do a proper
  * implementation.
  *
  * @return all providers that are attached to persons
  */
 private List<Object> getAllProvidersThatArePersons() {
   if (openmrsVersionDoesNotSupportProviders())
     throw new RuntimeException(
         "Programming error in HTML Form Entry module. This method should not be called before OpenMRS 1.9.");
   try {
     Object providerService =
         Context.getService(Context.loadClass("org.openmrs.api.ProviderService"));
     Method getProvidersMethod = providerService.getClass().getMethod("getAllProviders");
     @SuppressWarnings("rawtypes")
     List allProviders = (List) getProvidersMethod.invoke(providerService);
     List<Object> ret = new ArrayList<Object>();
     for (Object provider : allProviders) {
       Person person = (Person) PropertyUtils.getProperty(provider, "person");
       if (person != null) ret.add(provider);
     }
     return ret;
   } catch (Exception ex) {
     throw new RuntimeException(
         "Programming error in HTML Form Entry module. This method should be safe!", ex);
   }
 }
  public int doStartTag() {

    records = null;

    Locale locale = Context.getLocale();

    if (name.equals("patientIdentifierType")) {
      PatientService ps = Context.getPatientService();
      records = ps.getAllPatientIdentifierTypes().iterator();
    } else if (name.equals("relationshipType")) {
      PersonService ps = Context.getPersonService();
      records = ps.getAllRelationshipTypes().iterator();
    } else if (name.equals("encounterType")) {
      EncounterService es = Context.getEncounterService();
      records = es.getAllEncounterTypes().iterator();
    } else if (name.equals("location")) {
      LocationService locServ = Context.getLocationService();
      records = locServ.getAllLocations().iterator();
    } else if (name.equals("locationHierarchy")) {
      List<LocationAndDepth> locationAndDepths = new ArrayList<LocationAndDepth>();
      List<Location> locations = Context.getLocationService().getRootLocations(true);
      populateLocationAndDepthList(locationAndDepths, locations, 0);
      records = locationAndDepths.iterator();
    } else if (name.equals("cohort")) {
      List<Cohort> cohorts = Context.getCohortService().getAllCohorts();
      records = cohorts.iterator();
    } else if (name.equals("conceptSource")) {
      List<ConceptSource> conceptSources = Context.getConceptService().getAllConceptSources(false);
      records = conceptSources.iterator();
    } else if (name.equals("form")) {
      List<Form> forms = Context.getFormService().getAllForms();
      records = forms.iterator();
    } else if (name.equals("role")) {
      List<Role> roles = Context.getUserService().getAllRoles();
      records = roles.iterator();
    } else if (name.equals("conceptMapType")) {
      List<ConceptMapType> mapTypes = Context.getConceptService().getActiveConceptMapTypes();
      records = mapTypes.iterator();
    } else if (name.equals("civilStatus")) {
      ConceptService cs = Context.getConceptService();
      Concept civilStatus = cs.getConcept(OpenmrsConstants.CIVIL_STATUS_CONCEPT_ID);
      if (civilStatus == null) {
        log.error("OpenmrsConstants.CIVIL_STATUS_CONCEPT_ID is defined incorrectly.");
      } else {
        records = civilStatus.getAnswers(false).iterator();

        Map<String, String> opts = new HashMap<String, String>();
        for (ConceptAnswer a : civilStatus.getAnswers(false)) {
          opts.put(
              a.getAnswerConcept().getConceptId().toString(),
              a.getAnswerConcept().getShortestName(locale, false).getName());
        }
        records = opts.entrySet().iterator();
        if (select != null) {
          select = select.toString() + "=" + opts.get(select);
        }
      }
    } else if (name.equals("gender")) {
      Map<String, String> opts = OpenmrsConstants.GENDER();
      records = opts.entrySet().iterator();
      if (select != null) {
        select = select.toString() + "=" + opts.get(select);
      }
    } else if (name.equals("workflowStatus")) {
      List<ProgramWorkflowState> ret = new ArrayList<ProgramWorkflowState>();
      records = ret.iterator();
    } else if (name.equals("workflowProgram")) {
      List<org.openmrs.Program> ret = Context.getProgramWorkflowService().getAllPrograms();
      records = ret.iterator();
    } else if (name.equals("role")) {
      List<Role> ret = Context.getUserService().getAllRoles();
      records = ret.iterator();
    } else if (name.equals("conceptSet")) {
      if (conceptSet == null) {
        throw new IllegalArgumentException("Must specify conceptSet");
      }
      Concept c = Context.getConceptService().getConcept(conceptSet);
      if (c == null) {
        throw new IllegalArgumentException("Can't find conceptSet " + conceptSet);
      }
      List<Concept> list = Context.getConceptService().getConceptsByConceptSet(c);
      records = list.iterator();
    } else if (name.equals("answer")) {
      if (concept == null) {
        throw new IllegalArgumentException("Must specify concept");
      }
      Concept c = Context.getConceptService().getConcept(concept);
      if (c == null) {
        log.error(
            "Can't find concept with name or id of: "
                + concept
                + " and so no answers will be returned");
        records = null;
      } else if (c.getAnswers(false) != null) {
        records = c.getAnswers(false).iterator();
      } else {
        records = new ArrayList<Concept>().iterator();
      }
    } else {
      try {
        Class<?> cls = Context.loadClass(name);
        Constructor<?> ct = cls.getConstructor();
        Iterable<?> iterable = (Iterable<?>) ct.newInstance();
        records = iterable.iterator();

      } catch (Exception e) {
        log.error(name + " not found in ForEachRecord list " + e);
      }
    }

    if (records == null || !records.hasNext()) {
      records = null;
      return SKIP_BODY;
    } else {
      return EVAL_BODY_BUFFERED;
    }
  }