List of usage examples for java.lang Class getField
@CallerSensitive public Field getField(String name) throws NoSuchFieldException, SecurityException
From source file:nz.co.senanque.validationengine.metadata.AnnotationsMetadataFactory.java
public EngineMetadata getObject() throws Exception { final Map<Class<? extends Annotation>, Class<? extends FieldValidator<Annotation>>> validatorMap = getValidatorMap(); final Map<Class<?>, ClassMetadata> classMap = new HashMap<Class<?>, ClassMetadata>(); for (Class<?> clazz : m_classes) { log.debug("class name {}", clazz); boolean classNeeded = true; final ClassMetadata classMetadata = new ClassMetadata(); @SuppressWarnings("unchecked") Map<String, Property> propertyMap = ValidationUtils .getProperties((Class<? extends ValidationObject>) clazz); for (Property property : propertyMap.values()) { Method method = property.getGetter(); log.debug("method.getName() {}", method.getName()); String mname = method.getName(); final String fieldName = property.getFieldName(); final PropertyMetadataImpl fieldMetadata = new PropertyMetadataImpl(property, getMessageSource()); boolean fieldNeeded = false; boolean foundDigits = false; boolean foundLength = false; int digitsLength = -1; for (Annotation fieldAnnotation : method.getAnnotations()) { log.debug("field annotation {}", fieldAnnotation); if (fieldAnnotation instanceof Label) { fieldMetadata.setLabelName(((Label) fieldAnnotation).labelName()); fieldNeeded = true;// ww w.j a v a 2 s. co m } if (fieldAnnotation instanceof Inactive) { fieldMetadata.setInactive(true); fieldNeeded = true; } if (fieldAnnotation instanceof ReadOnly) { fieldMetadata.setReadOnly(true); fieldNeeded = true; } if (fieldAnnotation instanceof Secret) { fieldMetadata.setSecret(true); fieldNeeded = true; } if (fieldAnnotation instanceof Unknown) { fieldMetadata.setUnknown(true); fieldNeeded = true; } if (fieldAnnotation instanceof Required) { fieldMetadata.setRequired(true); fieldNeeded = true; } if (fieldAnnotation instanceof Digits) { fieldMetadata.setFractionalDigits(((Digits) fieldAnnotation).fractionalDigits()); fieldNeeded = true; foundDigits = true; digitsLength = Integer.parseInt(((Digits) fieldAnnotation).integerDigits()); foundLength = true; } if (fieldAnnotation instanceof Range) { fieldMetadata.setMinValue(((Range) fieldAnnotation).minInclusive()); fieldMetadata.setMaxValue(((Range) fieldAnnotation).maxInclusive()); fieldNeeded = true; } if (fieldAnnotation instanceof Description) { fieldMetadata.setDescription(((Description) fieldAnnotation).name()); fieldNeeded = true; } if (fieldAnnotation instanceof History) { fieldMetadata.setHistory(((History) fieldAnnotation).expire(), ((History) fieldAnnotation).entries()); fieldNeeded = true; } if (fieldAnnotation instanceof Id) { fieldMetadata.setIdentifier(true); } if (fieldAnnotation instanceof Regex) { fieldMetadata.setRegex(((Regex) fieldAnnotation).pattern()); fieldNeeded = true; } // if (fieldAnnotation instanceof BeanValidator) // { // fieldMetadata.setBean(((BeanValidator)fieldAnnotation).bean()); // fieldMetadata.setParam(((BeanValidator)fieldAnnotation).param()); // fieldNeeded = true; // } if (fieldAnnotation instanceof MapField) { fieldMetadata.setMapField(((MapField) fieldAnnotation).name()); fieldNeeded = true; } if (fieldAnnotation instanceof WritePermission) { fieldMetadata.setPermission(((WritePermission) fieldAnnotation).name()); fieldNeeded = true; } if (fieldAnnotation instanceof ReadPermission) { fieldMetadata.setReadPermission(((ReadPermission) fieldAnnotation).name()); fieldNeeded = true; } if (fieldAnnotation instanceof ChoiceList) { final List<ChoiceBase> choiceList = m_choicesMap.get(((ChoiceList) fieldAnnotation).name()); fieldMetadata.setChoiceList(choiceList); fieldNeeded = true; } if (fieldAnnotation instanceof Length) { fieldMetadata.setMaxLength(((Length) fieldAnnotation).maxLength()); fieldNeeded = true; foundLength = true; } Class<? extends FieldValidator<Annotation>> fvClass = validatorMap .get(fieldAnnotation.annotationType()); if (fvClass != null) { final FieldValidator<Annotation> fv = fvClass.newInstance(); fv.init(fieldAnnotation, fieldMetadata); fieldMetadata.addConstraintValidator(fv); fieldNeeded = true; } } Column column = method.getAnnotation(Column.class); if (column != null) { int precision = column.precision(); int fractional = column.scale(); int length = column.length(); if (!foundDigits) { if (fractional > 0) { fieldMetadata.setFractionalDigits(String.valueOf(fractional)); } } if (!foundLength) { if (precision > 0 && length == 255) { length = column.precision() + ((fractional > 0) ? 1 : 0); fieldMetadata.setMaxLength(String.valueOf(length)); } else { length = column.length(); fieldMetadata.setMaxLength(String.valueOf(length)); } } } Field field; try { field = clazz.getField(mname); for (Annotation fieldAnnotation : field.getAnnotations()) { if (fieldAnnotation instanceof XmlElement) { if (((XmlElement) fieldAnnotation).required()) { fieldMetadata.setRequired(true); fieldNeeded = true; } } } } catch (NoSuchFieldException e) { // ignore } Class<?> returnClass = method.getReturnType(); Object[] t = returnClass.getEnumConstants(); if (t != null) { fieldNeeded = true; fieldMetadata.setChoiceList(t); } if (!fieldNeeded) { if (m_classes.contains(returnClass) || returnClass.isAssignableFrom(List.class)) { fieldNeeded = true; } } if (fieldNeeded) { log.debug("fieldName added to metadata {}.{}", clazz.getName(), fieldName); classMetadata.addField(fieldName, fieldMetadata); classNeeded = true; } else { log.debug("fieldName not needed {}.{}", clazz.getName(), fieldName); } } if (classNeeded) { log.debug("Class added to metadata {}", clazz.getName()); classMap.put(clazz, classMetadata); } } return new EngineMetadata(classMap, m_choicesDoc); }
From source file:org.nextframework.controller.ExtendedBeanWrapper.java
/** * Convert the value to the required type (if necessary from a String), * for the specified property./* w ww .jav a 2s . c o m*/ * @param propertyName name of the property * @param oldValue previous value, if available (may be <code>null</code>) * @param newValue proposed change value * @param requiredType the type we must convert to * (or <code>null</code> if not known, for example in case of a collection element) * @return the new value, possibly the result of type conversion * @throws TypeMismatchException if type conversion failed */ protected Object doTypeConversionIfNecessary(String propertyName, String fullPropertyName, Object oldValue, Object newValue, Class requiredType) throws TypeMismatchException { Object convertedValue = newValue; if (convertedValue != null) { // Custom editor for this type? PropertyEditor pe = findCustomEditor(requiredType, fullPropertyName); // Value not of required type? if (pe != null || (requiredType != null && (requiredType.isArray() || !requiredType.isAssignableFrom(convertedValue.getClass())))) { if (requiredType != null) { if (pe == null) { // No custom editor -> check BeanWrapperImpl's default editors. pe = (PropertyEditor) this.defaultEditors.get(requiredType); if (pe == null) { // No BeanWrapper default editor -> check standard JavaBean editors. pe = PropertyEditorManager.findEditor(requiredType); } } } if (pe != null && !(convertedValue instanceof String)) { // Not a String -> use PropertyEditor's setValue. // With standard PropertyEditors, this will return the very same object; // we just want to allow special PropertyEditors to override setValue // for type conversion from non-String values to the required type. try { pe.setValue(convertedValue); Object newConvertedValue = pe.getValue(); if (newConvertedValue != convertedValue) { convertedValue = newConvertedValue; // Reset PropertyEditor: It already did a proper conversion. // Don't use it again for a setAsText call. pe = null; } } catch (IllegalArgumentException ex) { throw new TypeMismatchException( createPropertyChangeEvent(fullPropertyName, oldValue, newValue), requiredType, ex); } } if (requiredType != null && !requiredType.isArray() && convertedValue instanceof String[]) { // Convert String array to a comma-separated String. // Only applies if no PropertyEditor converted the String array before. // The CSV String will be passed into a PropertyEditor's setAsText method, if any. if (logger.isDebugEnabled()) { logger.debug("Converting String array to comma-delimited String [" + convertedValue + "]"); } convertedValue = StringUtils.arrayToCommaDelimitedString((String[]) convertedValue); } if (pe != null && convertedValue instanceof String) { // Use PropertyEditor's setAsText in case of a String value. if (logger.isDebugEnabled()) { logger.debug( "Converting String to [" + requiredType + "] using property editor [" + pe + "]"); } try { pe.setValue(oldValue); pe.setAsText((String) convertedValue); convertedValue = pe.getValue(); } catch (IllegalArgumentException ex) { throw new TypeMismatchException( createPropertyChangeEvent(fullPropertyName, oldValue, newValue), requiredType, ex); } } if (requiredType != null) { // Array required -> apply appropriate conversion of elements. if (requiredType.isArray()) { Class componentType = requiredType.getComponentType(); if (convertedValue instanceof Collection) { // Convert Collection elements to array elements. Collection coll = (Collection) convertedValue; Object result = Array.newInstance(componentType, coll.size()); int i = 0; for (Iterator it = coll.iterator(); it.hasNext(); i++) { Object value = doTypeConversionIfNecessary(propertyName, propertyName + PROPERTY_KEY_PREFIX + i + PROPERTY_KEY_SUFFIX, null, it.next(), componentType); Array.set(result, i, value); } return result; } else if (convertedValue != null && convertedValue.getClass().isArray()) { // Convert Collection elements to array elements. int arrayLength = Array.getLength(convertedValue); Object result = Array.newInstance(componentType, arrayLength); for (int i = 0; i < arrayLength; i++) { Object value = doTypeConversionIfNecessary(propertyName, propertyName + PROPERTY_KEY_PREFIX + i + PROPERTY_KEY_SUFFIX, null, Array.get(convertedValue, i), componentType); Array.set(result, i, value); } return result; } else { // A plain value: convert it to an array with a single component. Object result = Array.newInstance(componentType, 1); Object value = doTypeConversionIfNecessary(propertyName, propertyName + PROPERTY_KEY_PREFIX + 0 + PROPERTY_KEY_SUFFIX, null, convertedValue, componentType); Array.set(result, 0, value); return result; } } // If the resulting value definitely doesn't match the required type, // try field lookup as fallback. If no matching field found, // throw explicit TypeMismatchException with full context information. if (convertedValue != null && !requiredType.isPrimitive() && !requiredType.isAssignableFrom(convertedValue.getClass())) { // In case of String value, try to find matching field (for JDK 1.5 // enum or custom enum with values defined as static fields). if (convertedValue instanceof String) { try { Field enumField = requiredType.getField((String) convertedValue); return enumField.get(null); } catch (Exception ex) { logger.debug("Field [" + convertedValue + "] isn't an enum value", ex); } } // Definitely doesn't match: throw TypeMismatchException. throw new TypeMismatchException( createPropertyChangeEvent(fullPropertyName, oldValue, newValue), requiredType); } } } } if (requiredType != null && List.class.isAssignableFrom(requiredType)) { //treat conventions of enum lists Type genericReturnType = getPropertyDescriptorInternal(fullPropertyName).getReadMethod() .getGenericReturnType(); if (genericReturnType instanceof ParameterizedType) { Type actualType = ((ParameterizedType) genericReturnType).getActualTypeArguments()[0]; if (actualType instanceof Class && convertedValue != null) { List list = (List) convertedValue; for (int i = 0; i < list.size(); i++) { Object o = list.remove(i); o = doTypeConversionIfNecessary(o, (Class) actualType); list.add(i, o); } } } } return convertedValue; }
From source file:org.openTwoFactor.client.util.TwoFactorClientCommonUtils.java
/** * <p>Checks whether this <code>Throwable</code> class can store a cause.</p> * /*from w w w. ja v a 2 s .co m*/ * <p>This method does <b>not</b> check whether it actually does store a cause.<p> * * @param throwable the <code>Throwable</code> to examine, may be null * @return boolean <code>true</code> if nested otherwise <code>false</code> * @since 2.0 */ public static boolean isNestedThrowable(Throwable throwable) { if (throwable == null) { return false; } if (throwable instanceof SQLException) { return true; } else if (throwable instanceof InvocationTargetException) { return true; } else if (isThrowableNested()) { return true; } Class cls = throwable.getClass(); for (int i = 0, isize = CAUSE_METHOD_NAMES.length; i < isize; i++) { try { Method method = cls.getMethod(CAUSE_METHOD_NAMES[i], (Class[]) null); if (method != null && Throwable.class.isAssignableFrom(method.getReturnType())) { return true; } } catch (NoSuchMethodException ignored) { } catch (SecurityException ignored) { } } try { Field field = cls.getField("detail"); if (field != null) { return true; } } catch (NoSuchFieldException ignored) { } catch (SecurityException ignored) { } return false; }
From source file:com.clark.func.Functions.java
/** * <p>/*from w w w . java 2s . c om*/ * Removes the accents from a string. * </p> * <p> * NOTE: This is a JDK 1.6 method, it will fail on JDK 1.5. * </p> * * <pre> * stripAccents(null) = null * stripAccents("") = "" * stripAccents("control") = "control" * stripAccents("&ecute;clair") = "eclair" * </pre> * * @param input * String to be stripped * @return String without accents on the text * * @since 3.0 */ public static String stripAccents(String input) { if (input == null) { return null; } if (isJavaVersionAtLeast(1.6f)) { // String decomposed = Normalizer.normalize(input, // Normalizer.Form.NFD); // START of 1.5 reflection - in 1.6 use the line commented out above try { // get java.text.Normalizer.Form class Class<?> normalizerFormClass = getClass("java.text.Normalizer$Form", false); // get Normlizer class Class<?> normalizerClass = getClass("java.text.Normalizer", false); // get static method on Normalizer java.lang.reflect.Method method = normalizerClass.getMethod("normalize", CharSequence.class, normalizerFormClass); // get Normalizer.NFD field java.lang.reflect.Field nfd = normalizerFormClass.getField("NFD"); // invoke method String decomposed = (String) method.invoke(null, input, nfd.get(null)); // END of 1.5 reflection java.util.regex.Pattern accentPattern = java.util.regex.Pattern .compile("\\p{InCombiningDiacriticalMarks}+"); return accentPattern.matcher(decomposed).replaceAll(""); } catch (ClassNotFoundException cnfe) { throw new RuntimeException("ClassNotFoundException occurred during 1.6 backcompat code", cnfe); } catch (NoSuchMethodException nsme) { throw new RuntimeException("NoSuchMethodException occurred during 1.6 backcompat code", nsme); } catch (NoSuchFieldException nsfe) { throw new RuntimeException("NoSuchFieldException occurred during 1.6 backcompat code", nsfe); } catch (IllegalAccessException iae) { throw new RuntimeException("IllegalAccessException occurred during 1.6 backcompat code", iae); } catch (IllegalArgumentException iae) { throw new RuntimeException("IllegalArgumentException occurred during 1.6 backcompat code", iae); } catch (java.lang.reflect.InvocationTargetException ite) { throw new RuntimeException("InvocationTargetException occurred during 1.6 backcompat code", ite); } catch (SecurityException se) { throw new RuntimeException("SecurityException occurred during 1.6 backcompat code", se); } } else { throw new UnsupportedOperationException( "The stripAccents(String) method is not supported until Java 1.6"); } }