Example usage for org.springframework.beans.propertyeditors CustomDateEditor CustomDateEditor

List of usage examples for org.springframework.beans.propertyeditors CustomDateEditor CustomDateEditor

Introduction

In this page you can find the example usage for org.springframework.beans.propertyeditors CustomDateEditor CustomDateEditor.

Prototype

public CustomDateEditor(DateFormat dateFormat, boolean allowEmpty, int exactDateLength) 

Source Link

Document

Create a new CustomDateEditor instance, using the given DateFormat for parsing and rendering.

Usage

From source file:org.openmrs.module.programlocation.web.controller.PatientProgramFormController.java

public ModelAndView complete(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String returnPage = request.getParameter("returnPage");
    if (returnPage == null) {
        throw new IllegalArgumentException("must specify a returnPage parameter in a call to enroll()");
    }/*from   w  ww  .j  av  a  2 s .co m*/

    String patientProgramIdStr = request.getParameter("patientProgramId");
    String dateCompletedStr = request.getParameter("dateCompleted");

    // make sure we parse dates the same was as if we were using the initBinder + property editor method 
    CustomDateEditor cde = new CustomDateEditor(Context.getDateFormat(), true, 10);
    cde.setAsText(dateCompletedStr);
    Date dateCompleted = (Date) cde.getValue();

    org.openmrs.PatientProgram p = Context.getProgramWorkflowService()
            .getPatientProgram(Integer.valueOf(patientProgramIdStr));
    p.setDateCompleted(dateCompleted);
    Context.getProgramWorkflowService().savePatientProgram(p);

    return new ModelAndView(new RedirectView(returnPage));
}

From source file:org.openmrs.module.personalhr.web.controller.NewPatientFormController.java

/**
 * Allows for other Objects to be used as values in input tags. Normally, only strings and lists
 * are expected/*w  ww .  ja v  a 2s.c o m*/
 * 
 * @see org.springframework.web.servlet.mvc.BaseCommandController#initBinder(javax.servlet.http.HttpServletRequest,
 *      org.springframework.web.bind.ServletRequestDataBinder)
 */
@Override
protected void initBinder(final HttpServletRequest request, final ServletRequestDataBinder binder)
        throws Exception {
    super.initBinder(request, binder);

    final NumberFormat nf = NumberFormat.getInstance(Context.getLocale());
    binder.registerCustomEditor(java.lang.Integer.class,
            new CustomNumberEditor(java.lang.Integer.class, nf, true));
    binder.registerCustomEditor(java.util.Date.class, new CustomDateEditor(Context.getDateFormat(), true, 10));
    binder.registerCustomEditor(Location.class, new LocationEditor());
    binder.registerCustomEditor(Concept.class, "causeOfDeath", new ConceptEditor());
    request.getSession().setAttribute(WebConstants.OPENMRS_HEADER_USE_MINIMAL, "true");

}

From source file:org.openmrs.web.controller.program.PatientProgramFormController.java

public ModelAndView complete(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String returnPage = request.getParameter("returnPage");
    if (returnPage == null) {
        throw new IllegalArgumentException("must specify a returnPage parameter in a call to enroll()");
    }/*from   www  .j  a va  2  s .  co m*/

    String patientProgramIdStr = request.getParameter("patientProgramId");
    String dateCompletedStr = request.getParameter("dateCompleted");

    // make sure we parse dates the same was as if we were using the initBinder + property editor method 
    CustomDateEditor cde = new CustomDateEditor(Context.getDateFormat(), true, 10);
    cde.setAsText(dateCompletedStr);
    Date dateCompleted = (Date) cde.getValue();

    PatientProgram p = Context.getProgramWorkflowService()
            .getPatientProgram(Integer.valueOf(patientProgramIdStr));
    p.setDateCompleted(dateCompleted);
    try {
        String message = validateWithErrorCodes(p);
        if (message != null) {
            request.getSession().setAttribute(WebConstants.OPENMRS_ERROR_ATTR, message);
        } else {
            Context.getProgramWorkflowService().savePatientProgram(p);
        }
    } catch (APIException e) {
        request.getSession().setAttribute(WebConstants.OPENMRS_ERROR_ATTR, e.getMessage());
    }

    return new ModelAndView(new RedirectView(returnPage));
}

From source file:de.fau.amos4.web.EmployeeFormController.java

@InitBinder
public void initBinder(WebDataBinder binder) {
    binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("dd/MM/yyyy"), true, 10));
}

From source file:com.jd.survey.web.security.LoginController.java

@InitBinder
public void initBinder(WebDataBinder binder) {
    SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
    dateFormat.setLenient(false);//  ww  w .j  ava2s  .  co m
    binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true, 10));
}

From source file:org.openmrs.module.dataentrystatistics.web.controller.DataEntryStatisticsController.java

protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception {
    super.initBinder(request, binder);

    binder.registerCustomEditor(java.util.Date.class,
            new CustomDateEditor(OpenmrsUtil.getDateFormat(Context.getLocale()), true, 10));
}

From source file:org.openmrs.util.OpenmrsUtil.java

/**
 * Takes a String (e.g. a user-entered one) and parses it into an object of the specified class
 * //from   w  w  w .  j a  v  a2  s . c  o m
 * @param string
 * @param clazz
 * @return Object of type <code>clazz</code> with the data from <code>string</code>
 */
@SuppressWarnings("unchecked")
public static Object parse(String string, Class clazz) {
    try {
        // If there's a valueOf(String) method, just use that (will cover at
        // least String, Integer, Double, Boolean)
        Method valueOfMethod = null;
        try {
            valueOfMethod = clazz.getMethod("valueOf", String.class);
        } catch (NoSuchMethodException ex) {
        }
        if (valueOfMethod != null) {
            return valueOfMethod.invoke(null, string);
        } else if (clazz.isEnum()) {
            // Special-case for enum types
            List<Enum> constants = Arrays.asList((Enum[]) clazz.getEnumConstants());
            for (Enum e : constants) {
                if (e.toString().equals(string)) {
                    return e;
                }
            }
            throw new IllegalArgumentException(string + " is not a legal value of enum class " + clazz);
        } else if (String.class.equals(clazz)) {
            return string;
        } else if (Location.class.equals(clazz)) {
            try {
                Integer.parseInt(string);
                LocationEditor ed = new LocationEditor();
                ed.setAsText(string);
                return ed.getValue();
            } catch (NumberFormatException ex) {
                return Context.getLocationService().getLocation(string);
            }
        } else if (Concept.class.equals(clazz)) {
            ConceptEditor ed = new ConceptEditor();
            ed.setAsText(string);
            return ed.getValue();
        } else if (Program.class.equals(clazz)) {
            ProgramEditor ed = new ProgramEditor();
            ed.setAsText(string);
            return ed.getValue();
        } else if (ProgramWorkflowState.class.equals(clazz)) {
            ProgramWorkflowStateEditor ed = new ProgramWorkflowStateEditor();
            ed.setAsText(string);
            return ed.getValue();
        } else if (EncounterType.class.equals(clazz)) {
            EncounterTypeEditor ed = new EncounterTypeEditor();
            ed.setAsText(string);
            return ed.getValue();
        } else if (Form.class.equals(clazz)) {
            FormEditor ed = new FormEditor();
            ed.setAsText(string);
            return ed.getValue();
        } else if (Drug.class.equals(clazz)) {
            DrugEditor ed = new DrugEditor();
            ed.setAsText(string);
            return ed.getValue();
        } else if (PersonAttributeType.class.equals(clazz)) {
            PersonAttributeTypeEditor ed = new PersonAttributeTypeEditor();
            ed.setAsText(string);
            return ed.getValue();
        } else if (Cohort.class.equals(clazz)) {
            CohortEditor ed = new CohortEditor();
            ed.setAsText(string);
            return ed.getValue();
        } else if (Date.class.equals(clazz)) {
            // TODO: this uses the date format from the current session,
            // which could cause problems if the user changes it after
            // searching.
            CustomDateEditor ed = new CustomDateEditor(Context.getDateFormat(), true, 10);
            ed.setAsText(string);
            return ed.getValue();
        } else if (Object.class.equals(clazz)) {
            // TODO: Decide whether this is a hack. Currently setting Object
            // arguments with a String
            return string;
        } else {
            throw new IllegalArgumentException("Don't know how to handle class: " + clazz);
        }
    } catch (Exception ex) {
        log.error("error converting \"" + string + "\" to " + clazz, ex);
        throw new IllegalArgumentException(ex);
    }
}

From source file:org.openmrs.util.ReportingcompatibilityUtil.java

/**
 * Uses reflection to translate a PatientSearch into a PatientFilter
 *///from   www  . ja va  2  s .c o m
@SuppressWarnings("unchecked")
public static PatientFilter toPatientFilter(PatientSearch search, CohortSearchHistory history,
        EvaluationContext evalContext) {
    if (search.isSavedSearchReference()) {
        PatientSearch ps = ((PatientSearchReportObject) Context.getService(ReportObjectService.class)
                .getReportObject(search.getSavedSearchId())).getPatientSearch();
        return toPatientFilter(ps, history, evalContext);
    } else if (search.isSavedFilterReference()) {
        return Context.getService(ReportObjectService.class).getPatientFilterById(search.getSavedFilterId());
    } else if (search.isSavedCohortReference()) {
        Cohort c = Context.getCohortService().getCohort(search.getSavedCohortId());
        // to prevent lazy loading exceptions, cache the member ids here
        if (c != null) {
            c.getMemberIds().size();
        }
        return new CohortFilter(c);
    } else if (search.isComposition()) {
        if (history == null && search.requiresHistory()) {
            throw new IllegalArgumentException("You can't evaluate this search without a history");
        } else {
            return search.cloneCompositionAsFilter(history, evalContext);
        }
    } else {
        Class clz = search.getFilterClass();
        if (clz == null) {
            throw new IllegalArgumentException(
                    "search must be saved, composition, or must have a class specified");
        }
        log.debug("About to instantiate " + clz);
        PatientFilter pf = null;
        try {
            pf = (PatientFilter) clz.newInstance();
        } catch (Exception ex) {
            log.error("Couldn't instantiate a " + search.getFilterClass(), ex);
            return null;
        }
        Class[] stringSingleton = { String.class };
        if (search.getArguments() != null) {
            for (SearchArgument sa : search.getArguments()) {
                if (log.isDebugEnabled()) {
                    log.debug("Looking at (" + sa.getPropertyClass() + ") " + sa.getName() + " -> "
                            + sa.getValue());
                }
                PropertyDescriptor pd = null;
                try {
                    pd = new PropertyDescriptor(sa.getName(), clz);
                } catch (IntrospectionException ex) {
                    log.error("Error while examining property " + sa.getName(), ex);
                    continue;
                }
                Class<?> realPropertyType = pd.getPropertyType();

                // instantiate the value of the search argument
                String valueAsString = sa.getValue();
                String testForExpression = search.getArgumentValue(sa.getName());
                if (testForExpression != null) {
                    log.debug("Setting " + sa.getName() + " to: " + testForExpression);
                    if (evalContext != null && EvaluationContext.isExpression(testForExpression)) {
                        Object evaluated = evalContext.evaluateExpression(testForExpression);
                        if (evaluated != null) {
                            if (evaluated instanceof Date) {
                                valueAsString = Context.getDateFormat().format((Date) evaluated);
                            } else {
                                valueAsString = evaluated.toString();
                            }
                        }
                        log.debug("Evaluated " + sa.getName() + " to: " + valueAsString);
                    }
                }

                Object value = null;
                Class<?> valueClass = sa.getPropertyClass();
                try {
                    // If there's a valueOf(String) method, just use that
                    // (will cover at least String, Integer, Double,
                    // Boolean)
                    Method valueOfMethod = null;
                    try {
                        valueOfMethod = valueClass.getMethod("valueOf", stringSingleton);
                    } catch (NoSuchMethodException ex) {
                    }
                    if (valueOfMethod != null) {
                        Object[] holder = { valueAsString };
                        value = valueOfMethod.invoke(pf, holder);
                    } else if (realPropertyType.isEnum()) {
                        // Special-case for enum types
                        List<Enum> constants = Arrays.asList((Enum[]) realPropertyType.getEnumConstants());
                        for (Enum e : constants) {
                            if (e.toString().equals(valueAsString)) {
                                value = e;
                                break;
                            }
                        }
                    } else if (String.class.equals(valueClass)) {
                        value = valueAsString;
                    } else if (Location.class.equals(valueClass)) {
                        LocationEditor ed = new LocationEditor();
                        ed.setAsText(valueAsString);
                        value = ed.getValue();
                    } else if (Concept.class.equals(valueClass)) {
                        ConceptEditor ed = new ConceptEditor();
                        ed.setAsText(valueAsString);
                        value = ed.getValue();
                    } else if (Program.class.equals(valueClass)) {
                        ProgramEditor ed = new ProgramEditor();
                        ed.setAsText(valueAsString);
                        value = ed.getValue();
                    } else if (ProgramWorkflowState.class.equals(valueClass)) {
                        ProgramWorkflowStateEditor ed = new ProgramWorkflowStateEditor();
                        ed.setAsText(valueAsString);
                        value = ed.getValue();
                    } else if (EncounterType.class.equals(valueClass)) {
                        EncounterTypeEditor ed = new EncounterTypeEditor();
                        ed.setAsText(valueAsString);
                        value = ed.getValue();
                    } else if (Form.class.equals(valueClass)) {
                        FormEditor ed = new FormEditor();
                        ed.setAsText(valueAsString);
                        value = ed.getValue();
                    } else if (Drug.class.equals(valueClass)) {
                        DrugEditor ed = new DrugEditor();
                        ed.setAsText(valueAsString);
                        value = ed.getValue();
                    } else if (PersonAttributeType.class.equals(valueClass)) {
                        PersonAttributeTypeEditor ed = new PersonAttributeTypeEditor();
                        ed.setAsText(valueAsString);
                        value = ed.getValue();
                    } else if (Cohort.class.equals(valueClass)) {
                        CohortEditor ed = new CohortEditor();
                        ed.setAsText(valueAsString);
                        value = ed.getValue();
                    } else if (Date.class.equals(valueClass)) {
                        // TODO: this uses the date format from the current
                        // session, which could cause problems if the user
                        // changes it after searching.
                        DateFormat df = Context.getDateFormat(); // new
                        // SimpleDateFormat(OpenmrsConstants.OPENMRS_LOCALE_DATE_PATTERNS().get(Context.getLocale().toString().toLowerCase()),
                        // Context.getLocale());
                        CustomDateEditor ed = new CustomDateEditor(df, true, 10);
                        ed.setAsText(valueAsString);
                        value = ed.getValue();
                    } else if (LogicCriteria.class.equals(valueClass)) {
                        value = Context.getLogicService().parseString(valueAsString);
                    } else {
                        // TODO: Decide whether this is a hack. Currently
                        // setting Object arguments with a String
                        value = valueAsString;
                    }
                } catch (Exception ex) {
                    log.error("error converting \"" + valueAsString + "\" to " + valueClass, ex);
                    continue;
                }

                if (value != null) {

                    if (realPropertyType.isAssignableFrom(valueClass)) {
                        log.debug("setting value of " + sa.getName() + " to " + value);
                        try {
                            pd.getWriteMethod().invoke(pf, value);
                        } catch (Exception ex) {
                            log.error("Error setting value of " + sa.getName() + " to " + sa.getValue() + " -> "
                                    + value, ex);
                            continue;
                        }
                    } else if (Collection.class.isAssignableFrom(realPropertyType)) {
                        log.debug(sa.getName() + " is a Collection property");
                        // if realPropertyType is a collection, add this
                        // value to it (possibly after instantiating)
                        try {
                            Collection collection = (Collection) pd.getReadMethod().invoke(pf, (Object[]) null);
                            if (collection == null) {
                                // we need to instantiate this collection.
                                // I'm going with the following rules, which
                                // should be rethought:
                                // SortedSet -> TreeSet
                                // Set -> HashSet
                                // Otherwise -> ArrayList
                                if (SortedSet.class.isAssignableFrom(realPropertyType)) {
                                    collection = new TreeSet();
                                    log.debug("instantiated a TreeSet");
                                    pd.getWriteMethod().invoke(pf, collection);
                                } else if (Set.class.isAssignableFrom(realPropertyType)) {
                                    collection = new HashSet();
                                    log.debug("instantiated a HashSet");
                                    pd.getWriteMethod().invoke(pf, collection);
                                } else {
                                    collection = new ArrayList();
                                    log.debug("instantiated an ArrayList");
                                    pd.getWriteMethod().invoke(pf, collection);
                                }
                            }
                            collection.add(value);
                        } catch (Exception ex) {
                            log.error("Error instantiating collection for property " + sa.getName()
                                    + " whose class is " + realPropertyType, ex);
                            continue;
                        }
                    } else {
                        log.error(pf.getClass() + " . " + sa.getName() + " should be " + realPropertyType
                                + " but is given as " + valueClass);
                    }
                }
            }
        }
        log.debug("Returning " + pf);
        return pf;
    }
}

From source file:org.openmrs.web.controller.patient.NewPatientFormController.java

/**
 * Allows for other Objects to be used as values in input tags. Normally, only strings and lists
 * are expected// w ww  .j  av  a  2 s . c o  m
 * 
 * @see org.springframework.web.servlet.mvc.BaseCommandController#initBinder(javax.servlet.http.HttpServletRequest,
 *      org.springframework.web.bind.ServletRequestDataBinder)
 */
protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception {
    super.initBinder(request, binder);

    NumberFormat nf = NumberFormat.getInstance(Context.getLocale());
    binder.registerCustomEditor(java.lang.Integer.class,
            new CustomNumberEditor(java.lang.Integer.class, nf, true));
    binder.registerCustomEditor(java.util.Date.class, new CustomDateEditor(Context.getDateFormat(), true, 10));
    binder.registerCustomEditor(Location.class, new LocationEditor());
    binder.registerCustomEditor(Concept.class, "causeOfDeath", new ConceptEditor());
}