Example usage for java.lang Enum toString

List of usage examples for java.lang Enum toString

Introduction

In this page you can find the example usage for java.lang Enum toString.

Prototype

public String toString() 

Source Link

Document

Returns the name of this enum constant, as contained in the declaration.

Usage

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

/**
 * Uses reflection to translate a PatientSearch into a PatientFilter
 *//*from w  w  w  .  j  a  v a 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:com.doitnext.jsonschema.generator.SchemaGen.java

private static boolean handleObjectType(Class<?> classz, StringBuilder sb,
        JsonSchemaProperty propertyDescriptor, Map<String, String> declarations, boolean topLevel,
        String uriPrefix) {//from  w  ww . j a  va2s . c o m
    boolean result = false;
    String prepend = "";
    Map<String, Boolean> flags = new HashMap<String, Boolean>();
    flags.put("hasTitle", false);
    flags.put("hasDescription", false);
    flags.put("hasType", false);
    flags.put("hasEnum", false);

    if (classz.isEnum()) {
        sb.append("\"type\":\"string\",");
        sb.append("\"enum\":[");
        for (Enum<?> c : (Enum<?>[]) classz.getEnumConstants()) {
            sb.append("\"");
            sb.append(c.toString());
            sb.append("\", ");
        }
        sb.append("]");
        flags.put("hasType", true);
        flags.put("hasEnum", true);
        result = true;
    }
    if (!flags.get("hasType")) {
        sb.append(prepend);
        sb.append("\"type\":\"object\"");
        prepend = ", ";
        flags.put("hasType", true);
        result = true;
    }
    if (handlePropertyDescriptor(sb, propertyDescriptor, flags, prepend, result, uriPrefix)) {
        result = true;
    }
    JsonSchemaClass annotation = classz.getAnnotation(JsonSchemaClass.class);
    if (annotation != null) {
        if (result == true)
            prepend = ", ";

        if (!StringUtils.isEmpty(annotation.id())) {
            sb.append(prepend);
            sb.append("\"id\":\"" + annotation.id() + "\"");
            prepend = ", ";
        }
        if (!flags.get("hasTitle") && !StringUtils.isEmpty(annotation.title())) {
            sb.append(prepend);
            sb.append("\"title\":\"" + annotation.title() + "\"");
            prepend = ", ";
        }
        if (!flags.get("hasDescription") && !StringUtils.isEmpty(annotation.description())) {
            sb.append(prepend);
            sb.append("\"description\":\"" + annotation.description() + "\"");
            prepend = ", ";
        }
        result = true;
    }

    sb.append(prepend);
    sb.append("\"properties\":");
    handleProperties(classz, sb, declarations, uriPrefix);
    prepend = ", ";
    return result;
}

From source file:org.crazydog.util.spring.ObjectUtils.java

/**
 * Check whether the given array of enum constants contains a constant with the given name.
 * @param enumValues the enum values to check, typically the product of a call to MyEnum.values()
 * @param constant the constant name to find (must not be null or empty string)
 * @param caseSensitive whether case is significant in determining a match
 * @return whether the constant has been found in the given array
 *///www  .j  a  v  a  2  s  .c  om
public static boolean containsConstant(Enum<?>[] enumValues, String constant, boolean caseSensitive) {
    for (Enum<?> candidate : enumValues) {
        if (caseSensitive ? candidate.toString().equals(constant)
                : candidate.toString().equalsIgnoreCase(constant)) {
            return true;
        }
    }
    return false;
}

From source file:org.batoo.common.util.ObjectUtils.java

/**
 * Check whether the given array of enum constants contains a constant with the given name.
 * // w  w w.  j  a v a2  s .  co  m
 * @param enumValues
 *            the enum values to check, typically the product of a call to MyEnum.values()
 * @param constant
 *            the constant name to find (must not be null or empty string)
 * @param caseSensitive
 *            whether case is significant in determining a match
 * @return whether the constant has been found in the given array
 */
public static boolean containsConstant(Enum<?>[] enumValues, String constant, boolean caseSensitive) {
    for (final Enum<?> candidate : enumValues) {
        if (caseSensitive ? candidate.toString().equals(constant)
                : candidate.toString().equalsIgnoreCase(constant)) {
            return true;
        }
    }
    return false;
}

From source file:org.droidparts.inner.converter.EnumConverter.java

@Override
public <G1, G2> void putToContentValues(Class<Enum<?>> valueType, Class<G1> genericArg1, Class<G2> genericArg2,
        ContentValues cv, String key, Enum<?> val) {
    cv.put(key, val.toString());
}

From source file:org.droidparts.inner.converter.EnumConverter.java

@Override
public <G1, G2> void putToJSON(Class<Enum<?>> valType, Class<G1> genericArg1, Class<G2> genericArg2,
        JSONObject obj, String key, Enum<?> val) throws Exception {
    obj.put(key, val.toString());
}

From source file:org.apache.sqoop.model.MEnumInput.java

public void setValue(Enum value) {
    setValue(value.toString());
}

From source file:com.edmunds.etm.web.util.EtmFormat.java

/**
 * Formats an enum value as a string of capitilized words.
 *
 * @param value the enum to format/*  w  ww . j  av a2 s  .  c o  m*/
 * @return formatted string
 */
public String enumeration(Enum<?> value) {
    if (value == null) {
        return getEmptyString();
    }

    String str = value.toString().replace('_', ' ');
    return str.length() > 2 ? WordUtils.capitalizeFully(str) : str;
}

From source file:hu.bme.mit.trainbenchmark.generator.graph.GraphGenerator.java

private Object enumsToString(Object value) {
    if (value instanceof Enum) {
        final Enum<?> e = (Enum<?>) value;
        value = e.toString();
    }/*from ww  w  .j av a 2 s.  com*/
    return value;
}

From source file:org.opentestsystem.delivery.testreg.domain.EnumBasedXStreamConverter.java

@Override
@SuppressWarnings("unchecked")
public String toString(final Object obj) {
    String name = (caseStyleSource == null) ? obj.toString()
            : (isFullyCapitalize ? caseStyleSource.changeCaseFully(obj.toString())
                    : caseStyleSource.changeCase(obj.toString()));

    if (caseStyleTarget.equals(CaseStyle.TITLECASE_HANDLE_NULL_EMPTY) && isNullOrEmpty(name)) {
        return "";
    }/*from   w w w  .  j a v  a 2  s .c  om*/
    try {
        Enum enumVal = Enum.valueOf(enumType, name);
        return caseStyleTarget.changeCase(enumVal.toString());
    } catch (IllegalArgumentException iae) {
        return name;
    }
}