下面列出了怎么用java.beans.PropertyEditor的API类实例代码及写法,或者点击链接到github查看源代码。
public static Object getValueFromBeanInfoPropertyEditor(
Class<?> attrClass, String attrName, String attrValue,
Class<?> propertyEditorClass)
throws JasperException
{
try {
PropertyEditor pe = (PropertyEditor)propertyEditorClass.getConstructor().newInstance();
pe.setAsText(attrValue);
return pe.getValue();
} catch (Exception ex) {
throw new JasperException(
Localizer.getMessage("jsp.error.beans.property.conversion",
attrValue, attrClass.getName(), attrName,
ex.getMessage()));
}
}
@Test
public void testPatternEditor() {
final String REGEX = "a.*";
PropertyEditor patternEditor = new PatternEditor();
patternEditor.setAsText(REGEX);
assertEquals(Pattern.compile(REGEX).pattern(), ((Pattern) patternEditor.getValue()).pattern());
assertEquals(REGEX, patternEditor.getAsText());
patternEditor = new PatternEditor();
assertEquals("", patternEditor.getAsText());
patternEditor = new PatternEditor();
patternEditor.setAsText(null);
assertEquals("", patternEditor.getAsText());
}
/**
* This implementation delegates to the
* {@link #getPropertyEditorRegistry() PropertyEditorRegistry}'s
* editor lookup facility, if available.
*/
@Override
@Nullable
public PropertyEditor findEditor(@Nullable String field, @Nullable Class<?> valueType) {
PropertyEditorRegistry editorRegistry = getPropertyEditorRegistry();
if (editorRegistry != null) {
Class<?> valueTypeToUse = valueType;
if (valueTypeToUse == null) {
valueTypeToUse = getFieldType(field);
}
return editorRegistry.findCustomEditor(valueTypeToUse, fixedField(field));
}
else {
return null;
}
}
/**
* Formats the field value based on registered PropertyEditors.
* @see #getCustomEditor
*/
@Override
protected Object formatFieldValue(String field, @Nullable Object value) {
String fixedField = fixedField(field);
// Try custom editor...
PropertyEditor customEditor = getCustomEditor(fixedField);
if (customEditor != null) {
customEditor.setValue(value);
String textValue = customEditor.getAsText();
// If the PropertyEditor returned null, there is no appropriate
// text representation for this value: only use it if non-null.
if (textValue != null) {
return textValue;
}
}
if (this.conversionService != null) {
// Try custom converter...
TypeDescriptor fieldDesc = getPropertyAccessor().getPropertyTypeDescriptor(fixedField);
TypeDescriptor strDesc = TypeDescriptor.valueOf(String.class);
if (fieldDesc != null && this.conversionService.canConvert(fieldDesc, strDesc)) {
return this.conversionService.convert(value, fieldDesc, strDesc);
}
}
return value;
}
/** Getter for the state of the property editor. The editor can be in
* not valid states just if it implements the <link>ExPropertyEditor</link>
* and changes state by the <code>setState</code> method of the <link>PropertyEnv</link>
* environment.
* <P>
* @return <code>PropertyEnv.STATE_VALID</code> if the editor is not the <code>ExPropertyEditor</code>
* one or other constant from <code>PropertyEnv.STATE_*</code> that was assigned to <code>PropertyEnv</code>
* @since 2.20
*/
public final Object getState() {
if ((displayer != null) && displayer instanceof PropertyDisplayer_Editable) {
return ((PropertyDisplayer_Editable) displayer).getPropertyEnv().getState();
} else {
PropertyEditor ed = propertyEditor();
if (ed instanceof ExPropertyEditor) {
//XXX until we kill ReusablePropertyModel, anyway
ReusablePropertyEnv env = reusableEnv;
reusableModel.setProperty(prop);
((ExPropertyEditor) ed).attachEnv(env);
return env.getState();
}
}
return PropertyEnv.STATE_VALID;
}
public PropertyEditor getEditorForCell( final int rowIndex, final int columnIndex ) {
final StyleMetaData metaData = getMetaData( rowIndex );
if ( metaData == null ) {
return null;
}
switch( columnIndex ) {
case 0:
return null;
case 1:
return null;
case 2:
return computeEditor( metaData, rowIndex );
default:
throw new IndexOutOfBoundsException();
}
}
@Test
public void testCustomEditorConfigurerWithRequiredTypeArray() throws ParseException {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
CustomEditorConfigurer cec = new CustomEditorConfigurer();
Map<Class<?>, Class<? extends PropertyEditor>> editors = new HashMap<>();
editors.put(String[].class, MyTestEditor.class);
cec.setCustomEditors(editors);
cec.postProcessBeanFactory(bf);
MutablePropertyValues pvs = new MutablePropertyValues();
pvs.add("stringArray", "xxx");
RootBeanDefinition bd = new RootBeanDefinition(TestBean.class);
bd.setPropertyValues(pvs);
bf.registerBeanDefinition("tb", bd);
TestBean tb = (TestBean) bf.getBean("tb");
assertTrue(tb.getStringArray() != null && tb.getStringArray().length == 1);
assertEquals("test", tb.getStringArray()[0]);
}
@Test
public void asBodyTagWithEditor() throws Exception {
String selectName = "testBean.stringArray";
BindStatus bindStatus = new BindStatus(getRequestContext(), selectName, false) {
@Override
public PropertyEditor getEditor() {
return new RulesVariantEditor();
}
};
getPageContext().setAttribute(SelectTag.LIST_VALUE_PAGE_ATTRIBUTE, bindStatus);
RulesVariant rulesVariant = new RulesVariant("someRules", "someVariant");
this.tag.setValue(rulesVariant);
int result = this.tag.doStartTag();
assertEquals(BodyTag.EVAL_BODY_BUFFERED, result);
assertEquals(rulesVariant, getPageContext().getAttribute("value"));
assertEquals(rulesVariant.toId(), getPageContext().getAttribute("displayValue"));
result = this.tag.doEndTag();
assertEquals(Tag.EVAL_PAGE, result);
}
private PropertyEditor getPropertyEditor(Class<?> requiredType) {
// Special case: If no required type specified, which usually only happens for
// Collection elements, or required type is not assignable to registered type,
// which usually only happens for generic properties of type Object -
// then return PropertyEditor if not registered for Collection or array type.
// (If not registered for Collection or array, it is assumed to be intended
// for elements.)
if (this.registeredType == null ||
(requiredType != null &&
(ClassUtils.isAssignable(this.registeredType, requiredType) ||
ClassUtils.isAssignable(requiredType, this.registeredType))) ||
(requiredType == null &&
(!Collection.class.isAssignableFrom(this.registeredType) && !this.registeredType.isArray()))) {
return this.propertyEditor;
}
else {
return null;
}
}
@Override
public void registerCustomEditor(Class<?> requiredType, String propertyPath, PropertyEditor propertyEditor) {
if (requiredType == null && propertyPath == null) {
throw new IllegalArgumentException("Either requiredType or propertyPath is required");
}
if (propertyPath != null) {
if (this.customEditorsForPath == null) {
this.customEditorsForPath = new LinkedHashMap<String, CustomEditorHolder>(16);
}
this.customEditorsForPath.put(propertyPath, new CustomEditorHolder(propertyEditor, requiredType));
}
else {
if (this.customEditors == null) {
this.customEditors = new LinkedHashMap<Class<?>, PropertyEditor>(16);
}
this.customEditors.put(requiredType, propertyEditor);
this.customEditorCache = null;
}
}
/**
* Locate a property editor for qiven class of object.
*
* @param type The target object class of the property.
* @return The resolved editor, if any. Returns null if a suitable editor
* could not be located.
*/
private static PropertyEditor findEditor(final Class type) {
if (type == null) {
throw new NullPointerException("type is null");
}
// try to locate this directly from the editor manager first.
final PropertyEditor editor = PropertyEditorManager.findEditor(type);
// we're outta here if we got one.
if (editor != null) {
return editor;
}
// nothing found
return null;
}
private static PropertyEditor findThePropertyEditor(Class clazz) {
PropertyEditor pe;
if (Object.class.equals(clazz)) {
pe = null;
} else {
pe = PropertyEditorManager.findEditor(clazz);
if (pe == null) {
Class sclazz = clazz.getSuperclass();
if (sclazz != null) {
pe = findPropertyEditor(sclazz);
}
}
}
classesWithPE.put(clazz, pe != null);
return pe;
}
public PropertyEditor getEditorForCell( final int rowIndex, final int columnIndex ) {
final AttributeMetaData metaData = getMetaData( rowIndex );
if ( metaData == null ) {
return null;
}
switch( columnIndex ) {
case 0:
return null;
case 1:
return computeEditor( metaData, rowIndex );
case 2:
return null;
default:
throw new IndexOutOfBoundsException();
}
}
@Test
public void testCustomEditorConfigurerWithEditorAsClass() throws ParseException {
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
CustomEditorConfigurer cec = new CustomEditorConfigurer();
Map<Class<?>, Class<? extends PropertyEditor>> editors = new HashMap<Class<?>, Class<? extends PropertyEditor>>();
editors.put(Date.class, MyDateEditor.class);
cec.setCustomEditors(editors);
cec.postProcessBeanFactory(bf);
MutablePropertyValues pvs = new MutablePropertyValues();
pvs.add("date", "2.12.1975");
RootBeanDefinition bd = new RootBeanDefinition(TestBean.class);
bd.setPropertyValues(pvs);
bf.registerBeanDefinition("tb", bd);
TestBean tb = (TestBean) bf.getBean("tb");
DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT, Locale.GERMAN);
assertEquals(df.parse("2.12.1975"), tb.getDate());
}
public String getAsText(Object object) {
PropertyEditor editor = fetchFromPool();
try {
editor.setValue(object);
return editor.getAsText();
} finally {
pool.putInPool(editor);
}
}
public TableCellRenderer getCellRenderer( final int row, final int viewColumn ) {
final TableModel tableModel = getModel();
if ( tableModel instanceof PropertyTableModel ) {
final PropertyTableModel model = (PropertyTableModel) getModel();
final int column = convertColumnIndexToModel( viewColumn );
final Class columnClass = model.getClassForCell( row, column );
if ( columnClass.isArray() ) {
return arrayCellRenderer;
}
final PropertyEditor propertyEditor = model.getEditorForCell( row, column );
if ( propertyEditor != null ) {
propertyEditorCellRenderer.setPropertyEditor( propertyEditor );
return propertyEditorCellRenderer;
}
final TableColumn tableColumn = getColumnModel().getColumn( column );
final TableCellRenderer renderer = tableColumn.getCellRenderer();
if ( renderer != null ) {
return renderer;
}
final TableCellRenderer defaultRenderer = getDefaultRenderer( columnClass );
if ( defaultRenderer != null ) {
return defaultRenderer;
}
if ( logger.isTraceEnabled() ) {
logger.trace( "No renderer for column class " + columnClass ); // NON-NLS
}
return getDefaultRenderer( Object.class );
}
return super.getCellRenderer( row, viewColumn );
}
/**
* Initialize the given PropertyEditorRegistry with the custom editors
* that have been registered with this BeanFactory.
* <p>To be called for BeanWrappers that will create and populate bean
* instances, and for SimpleTypeConverter used for constructor argument
* and factory method type conversion.
* @param registry the PropertyEditorRegistry to initialize
*/
protected void registerCustomEditors(PropertyEditorRegistry registry) {
PropertyEditorRegistrySupport registrySupport =
(registry instanceof PropertyEditorRegistrySupport ? (PropertyEditorRegistrySupport) registry : null);
if (registrySupport != null) {
registrySupport.useConfigValueEditors();
}
if (!this.propertyEditorRegistrars.isEmpty()) {
for (PropertyEditorRegistrar registrar : this.propertyEditorRegistrars) {
try {
registrar.registerCustomEditors(registry);
}
catch (BeanCreationException ex) {
Throwable rootCause = ex.getMostSpecificCause();
if (rootCause instanceof BeanCurrentlyInCreationException) {
BeanCreationException bce = (BeanCreationException) rootCause;
if (isCurrentlyInCreation(bce.getBeanName())) {
if (logger.isDebugEnabled()) {
logger.debug("PropertyEditorRegistrar [" + registrar.getClass().getName() +
"] failed because it tried to obtain currently created bean '" +
ex.getBeanName() + "': " + ex.getMessage());
}
onSuppressedException(ex);
continue;
}
}
throw ex;
}
}
}
if (!this.customEditors.isEmpty()) {
for (Map.Entry<Class<?>, Class<? extends PropertyEditor>> entry : this.customEditors.entrySet()) {
Class<?> requiredType = entry.getKey();
Class<? extends PropertyEditor> editorClass = entry.getValue();
registry.registerCustomEditor(requiredType, BeanUtils.instantiateClass(editorClass));
}
}
}
@Override
public PropertyEditor getPropertyEditor() {
try {
return new RevisionPropertyEditor(getValue());
} catch (Exception e) {
return super.getPropertyEditor();
}
}
public PropertyEditorFinder() {
super(PropertyEditor.class, false, "Editor", DEFAULT);
this.registry = new WeakCache<Class<?>, Class<?>>();
this.registry.put(Byte.TYPE, ByteEditor.class);
this.registry.put(Short.TYPE, ShortEditor.class);
this.registry.put(Integer.TYPE, IntegerEditor.class);
this.registry.put(Long.TYPE, LongEditor.class);
this.registry.put(Boolean.TYPE, BooleanEditor.class);
this.registry.put(Float.TYPE, FloatEditor.class);
this.registry.put(Double.TYPE, DoubleEditor.class);
}
public void testEnumPropEd() throws Exception {
EProp prop = new EProp();
PropertyEditor ed = PropUtils.getPropertyEditor(prop);
assertEquals( EnumPropertyEditor.class, ed.getClass());
assertFalse(ed.supportsCustomEditor());
assertFalse(ed.isPaintable());
String[] tags = ed.getTags();
assertNotNull(tags);
assertEquals("[CHOCOLATE, VANILLA, STRAWBERRY]", Arrays.toString(tags));
assertEquals(E.VANILLA, ed.getValue());
assertEquals("VANILLA", ed.getAsText());
ed.setAsText("STRAWBERRY");
assertEquals(E.STRAWBERRY, ed.getValue());
assertEquals(E.class.getName().replace('$', '.') + ".STRAWBERRY", ed.getJavaInitializationString());
}
public void connect(PropertyEditor propertyEditor, PropertyEnv env) {
editor = propertyEditor;
mdl = ViewDB.getCurrentModel();
// replace ViewDB.getCurrentModel() with model from object being edited
if (env.getBeans().length >0 && env.getBeans()[0] instanceof OpenSimObjectNode){
mdl = ((OpenSimObjectNode) env.getBeans()[0]).getModelForNode();
}
SingleModelGuiElements modelGuiElems = OpenSimDB.getInstance().getModelGuiElements(mdl);
picker.setModel(new DefaultComboBoxModel(modelGuiElems.getFrameNames()));
reset();
}
public boolean performEdit( final PropertyEditor editor ) {
if ( editor == null ) {
throw new NullPointerException();
}
final Object originalValue = editor.getValue();
final Component view = editor.getCustomEditor();
if ( view instanceof ValidatingPropertyEditorComponent ) {
validatingView = (ValidatingPropertyEditorComponent) view;
validatingView.addPropertyChangeListener( validationHandler );
} else {
validatingView = null;
}
contentPane.removeAll();
contentPane.add( new JScrollPane( view ), BorderLayout.CENTER );
if ( super.performEdit() == false ) {
try {
editor.setValue( originalValue );
} catch ( Exception ex ) {
// ignore ..
}
}
if ( validatingView != null ) {
validatingView.removePropertyChangeListener( validationHandler );
}
return isConfirmed();
}
@Test
public void encodeAlreadyEncodedURI() throws Exception {
PropertyEditor uriEditor = new URIEditor(false);
uriEditor.setAsText("http://example.com/spaces%20and%20%E2%82%AC");
Object value = uriEditor.getValue();
assertTrue(value instanceof URI);
URI uri = (URI) value;
assertEquals(uri.toString(), uriEditor.getAsText());
assertEquals("http://example.com/spaces%20and%20%E2%82%AC", uri.toASCIIString());
}
@Test
public void testSystemPropertyReplacement() {
PropertyEditor editor = new ResourceArrayPropertyEditor();
System.setProperty("test.prop", "foo");
try {
editor.setAsText("${test.prop}-${bar}");
Resource[] resources = (Resource[]) editor.getValue();
assertEquals("foo-${bar}", resources[0].getFilename());
}
finally {
System.getProperties().remove("test.prop");
}
}
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
if (this.propertyEditorRegistrars != null) {
for (PropertyEditorRegistrar propertyEditorRegistrar : this.propertyEditorRegistrars) {
beanFactory.addPropertyEditorRegistrar(propertyEditorRegistrar);
}
}
if (this.customEditors != null) {
for (Map.Entry<Class<?>, Class<? extends PropertyEditor>> entry : this.customEditors.entrySet()) {
Class<?> requiredType = entry.getKey();
Class<? extends PropertyEditor> propertyEditorClass = entry.getValue();
beanFactory.registerCustomEditor(requiredType, propertyEditorClass);
}
}
}
@Test
public void allowEmptyプロパティの設定が反映される() {
registry = new ExtendedServletRequestDataBinder(new TestBean());
registrar = new JseDefaultDatePropertyEditorRegistrar();
registrar.setAllowEmpty(true);
registrar.registerCustomEditors(registry);
PropertyEditor editor = registry.findCustomEditor(Date.class, "birth");
DateEditor dateEditor = (DateEditor)editor;
dateEditor.setAsText(null);
assertThat(dateEditor.getAsText(), is(""));
}
public void testNulls() throws Exception {
EProp prop = new EProp();
PropertyEditor ed = PropUtils.getPropertyEditor(prop);
assertEquals( EnumPropertyEditor.class, ed.getClass());
ed.setAsText("");
assertEquals(null, ed.getValue());
assertEquals("", ed.getAsText());
assertEquals("null", ed.getJavaInitializationString());
}
@Override
public PropertyEditor getPropertyEditor() {
if (editor != null) {
return editor;
}
return super.getPropertyEditor();
}
public PropertyEditor getEditor() {
if ( propertyEditorClass == null ) {
return null;
}
try {
return propertyEditorClass.newInstance();
} catch ( Exception e ) {
logger.warn( "Property editor for expression property '" + getName() + "' threw an Exception on instantiate", e );
return null;
}
}
/**
* @throws IllegalStateException
* if the class of the cache model to create has not been set.
* @see SemicolonSeparatedPropertiesParser#parseProperties(String)
* @see PropertyEditor#setAsText(String)
* @see org.springframework.beans.PropertyAccessor#setPropertyValue(String,
* Object)
*/
public final void setAsText(String text) {
if (cacheModelClass == null) {
throw new IllegalStateException("cacheModelClass should not be null");
}
Properties properties = SemicolonSeparatedPropertiesParser
.parseProperties(text);
BeanWrapper beanWrapper = new BeanWrapperImpl(cacheModelClass);
if (properties != null) {
for (Iterator i = properties.keySet().iterator(); i.hasNext();) {
String propertyName = (String) i.next();
String textProperty = properties.getProperty(propertyName);
Object propertyValue = null;
PropertyEditor propertyEditor = getPropertyEditor(propertyName);
if (propertyEditor != null) {
propertyEditor.setAsText(textProperty);
propertyValue = propertyEditor.getValue();
} else {
propertyValue = textProperty;
}
beanWrapper.setPropertyValue(propertyName, propertyValue);
}
}
setValue(beanWrapper.getWrappedInstance());
}