java.beans.PropertyEditor Java Examples

The following examples show how to use java.beans.PropertyEditor. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ValuePropertyEditor.java    From netbeans with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #2
Source File: AbstractPropertyBindingResult.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * 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;
}
 
Example #3
Source File: AbstractBindingResult.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * 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;
	}
}
 
Example #4
Source File: CustomEditorConfigurerTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@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());
}
 
Example #5
Source File: CustomEditorTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@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());
}
 
Example #6
Source File: JspRuntimeLibrary.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
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()));
    }
}
 
Example #7
Source File: VisualAttributeTableModel.java    From pentaho-reporting with GNU Lesser General Public License v2.1 6 votes vote down vote up
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();
  }
}
 
Example #8
Source File: ClientInjectionProcessor.java    From tomee with Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #9
Source File: PropertyEditorRegistrySupport.java    From blog_demos with Apache License 2.0 6 votes vote down vote up
@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;
	}
}
 
Example #10
Source File: PropertyEditorRegistrySupport.java    From blog_demos with Apache License 2.0 6 votes vote down vote up
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;
	}
}
 
Example #11
Source File: OptionTagTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@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);
}
 
Example #12
Source File: CustomEditorConfigurerTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@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]);
}
 
Example #13
Source File: PropertyPanel.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/** 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;
}
 
Example #14
Source File: AbstractStyleTableModel.java    From pentaho-reporting with GNU Lesser General Public License v2.1 6 votes vote down vote up
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();
  }
}
 
Example #15
Source File: TypeConverterDelegate.java    From blog_demos with Apache License 2.0 5 votes vote down vote up
/**
 * Find a default editor for the given type.
 * @param requiredType the type to find an editor for
 * @return the corresponding editor, or {@code null} if none
 */
private PropertyEditor findDefaultEditor(Class<?> requiredType) {
	PropertyEditor editor = null;
	if (requiredType != null) {
		// No custom editor -> check BeanWrapperImpl's default editors.
		editor = this.propertyEditorRegistry.getDefaultEditor(requiredType);
		if (editor == null && !String.class.equals(requiredType)) {
			// No BeanWrapper default editor -> check standard JavaBean editor.
			editor = BeanUtils.findEditorByConvention(requiredType);
		}
	}
	return editor;
}
 
Example #16
Source File: ResourceEditorTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void sunnyDay() throws Exception {
	PropertyEditor editor = new ResourceEditor();
	editor.setAsText("classpath:org/springframework/core/io/ResourceEditorTests.class");
	Resource resource = (Resource) editor.getValue();
	assertNotNull(resource);
	assertTrue(resource.exists());
}
 
Example #17
Source File: PojoEncoder.java    From metafacture-core with Apache License 2.0 5 votes vote down vote up
private static Object createObjectFromString(final String value,
        final Class<?> targetType) {
    final PropertyEditor propertyEditor = PropertyEditorManager
            .findEditor(targetType);
    propertyEditor.setAsText(value);
    return propertyEditor.getValue();
}
 
Example #18
Source File: PropertyEditorFinder.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
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);
}
 
Example #19
Source File: DefaultStyleKeyMetaData.java    From pentaho-reporting with GNU Lesser General Public License v2.1 5 votes vote down vote up
public PropertyEditor getEditor() {
  if ( propertyEditorClass == null ) {
    return null;
  }
  try {
    return propertyEditorClass.newInstance();
  } catch ( Exception e ) {
    logger.warn( "Property editor threw error on instantiation", e );
    return null;
  }
}
 
Example #20
Source File: ResourceEditorTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test(expected=IllegalArgumentException.class)
public void testStrictSystemPropertyReplacement() {
	PropertyEditor editor = new ResourceEditor(new DefaultResourceLoader(), new StandardEnvironment(), false);
	System.setProperty("test.prop", "foo");
	try {
		editor.setAsText("${test.prop}-${bar}");
		Resource resolved = (Resource) editor.getValue();
		assertEquals("foo-${bar}", resolved.getFilename());
	}
	finally {
		System.getProperties().remove("test.prop");
	}
}
 
Example #21
Source File: DefaultExpressionPropertyMetaData.java    From pentaho-reporting with GNU Lesser General Public License v2.1 5 votes vote down vote up
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;
  }
}
 
Example #22
Source File: OptionTagTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void withPropertyEditorStringComparison() throws Exception {
	final PropertyEditor testBeanEditor = new TestBeanPropertyEditor();
	testBeanEditor.setValue(new TestBean("Sally"));
	String selectName = "testBean.spouse";
	BindStatus bindStatus = new BindStatus(getRequestContext(), selectName, false) {
		@Override
		public PropertyEditor getEditor() {
			return testBeanEditor;
		}
	};
	getPageContext().setAttribute(SelectTag.LIST_VALUE_PAGE_ATTRIBUTE, bindStatus);

	this.tag.setValue("Sally");

	int result = this.tag.doStartTag();
	assertEquals(BodyTag.EVAL_BODY_BUFFERED, result);
	result = this.tag.doEndTag();
	assertEquals(Tag.EVAL_PAGE, result);

	String output = getOutput();
	assertOptionTagOpened(output);
	assertOptionTagClosed(output);
	assertContainsAttribute(output, "value", "Sally");
	assertContainsAttribute(output, "selected", "selected");
	assertBlockTagContains(output, "Sally");
}
 
Example #23
Source File: TestPropertyEditor.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
private static void test(Class<?> type, Class<? extends PropertyEditor> expected) {
    PropertyEditor actual = PropertyEditorManager.findEditor(type);
    if ((actual == null) && (expected != null)) {
        throw new Error("expected editor is not found");
    }
    if ((actual != null) && !actual.getClass().equals(expected)) {
        throw new Error("found unexpected editor");
    }
}
 
Example #24
Source File: FormCodeSupport.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public String getJavaCodeString(String parentStr, String[] paramsStr) {
    try {
        PropertyEditor pred = property.getPropertyEditor();
        pred.setValue(property.getValue());
        return pred.getJavaInitializationString();
    }
    catch (Exception ex) {} // should not happen
    return null;
}
 
Example #25
Source File: ThreadSafePropertyEditor.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public String getAsText(Object object) {
    PropertyEditor editor = fetchFromPool();
    try {
        editor.setValue(object);
        return editor.getAsText();
    } finally {
        pool.putInPool(editor);
    }
}
 
Example #26
Source File: ResourceArrayPropertyEditorTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void testPatternResource() throws Exception {
	// N.B. this will sometimes fail if you use classpath: instead of classpath*:.
	// The result depends on the classpath - if test-classes are segregated from classes
	// and they come first on the classpath (like in Maven) then it breaks, if classes
	// comes first (like in Spring Build) then it is OK.
	PropertyEditor editor = new ResourceArrayPropertyEditor();
	editor.setAsText("classpath*:org/springframework/core/io/support/Resource*Editor.class");
	Resource[] resources = (Resource[]) editor.getValue();
	assertNotNull(resources);
	assertTrue(resources[0].exists());
}
 
Example #27
Source File: OptionsPanel.java    From ghidra with Apache License 2.0 5 votes vote down vote up
private void addDetails(Options options, String optionName, List<String> results) {
	// some options use property editor classes to handle options editing and not 
	// EditableOptions objects directly
	PropertyEditor propertyEditor = options.getRegisteredPropertyEditor(optionName);
	if (propertyEditor instanceof CustomOptionsEditor) {
		addOptionDetails((CustomOptionsEditor) propertyEditor, results);
	}
	else {
		String description = options.getDescription(optionName);
		results.add(optionName);
		results.add(description);
	}
}
 
Example #28
Source File: ResourceEditorRegistrar.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Override default editor, if possible (since that's what we really mean to do here);
 * otherwise register as a custom editor.
 */
private void doRegisterEditor(PropertyEditorRegistry registry, Class<?> requiredType, PropertyEditor editor) {
	if (registry instanceof PropertyEditorRegistrySupport) {
		((PropertyEditorRegistrySupport) registry).overrideDefaultEditor(requiredType, editor);
	}
	else {
		registry.registerCustomEditor(requiredType, editor);
	}
}
 
Example #29
Source File: ReflectionCacheModelEditor.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * @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());
}
 
Example #30
Source File: DynamicParsers.java    From type-parser with MIT License 5 votes vote down vote up
@Override
public Object parseImp(String input, ParserHelper helper) {
    PropertyEditor editor = findEditor(helper.getRawTargetClass());
    if (editor == null) {
        return TRY_NEXT;
    }
    editor.setAsText(input);
    return editor.getValue();
}