java.beans.PropertyEditor#setValue ( )源码实例Demo

下面列出了java.beans.PropertyEditor#setValue ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: lams   文件: ValueFormatter.java
/**
 * Build the display value of the supplied {@code Object}, HTML escaped
 * as required. If the supplied value is not a {@link String} and the supplied
 * {@link PropertyEditor} is not null then the {@link PropertyEditor} is used
 * to obtain the display value.
 * @see #getDisplayString(Object, boolean)
 */
public static String getDisplayString(Object value, PropertyEditor propertyEditor, boolean htmlEscape) {
	if (propertyEditor != null && !(value instanceof String)) {
		try {
			propertyEditor.setValue(value);
			String text = propertyEditor.getAsText();
			if (text != null) {
				return getDisplayString(text, htmlEscape);
			}
		}
		catch (Throwable ex) {
			// The PropertyEditor might not support this value... pass through.
		}
	}
	return getDisplayString(value, htmlEscape);
}
 
源代码2 项目: java-technology-stack   文件: ValueFormatter.java
/**
 * Build the display value of the supplied {@code Object}, HTML escaped
 * as required. If the supplied value is not a {@link String} and the supplied
 * {@link PropertyEditor} is not null then the {@link PropertyEditor} is used
 * to obtain the display value.
 * @see #getDisplayString(Object, boolean)
 */
public static String getDisplayString(
		@Nullable Object value, @Nullable PropertyEditor propertyEditor, boolean htmlEscape) {

	if (propertyEditor != null && !(value instanceof String)) {
		try {
			propertyEditor.setValue(value);
			String text = propertyEditor.getAsText();
			if (text != null) {
				return getDisplayString(text, htmlEscape);
			}
		}
		catch (Throwable ex) {
			// The PropertyEditor might not support this value... pass through.
		}
	}
	return getDisplayString(value, htmlEscape);
}
 
源代码3 项目: netbeans   文件: FormCodeSupport.java
@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;
}
 
源代码4 项目: netbeans   文件: CustomEditorDisplayer.java
public String isModifiedValueLegal() {
    boolean legal = true;
    String msg = null;
    PropertyEditor editor = getPropertyEditor();

    //        System.err.println("IS MODIFIED VALUE LEGAL");
    if (env != null) {
        legal = env.getState() != env.STATE_INVALID;

        System.err.println(" Attempting to validate env");

        if (legal && env.STATE_NEEDS_VALIDATION.equals(env.getState())) {
            msg = env.silentlySetState(env.STATE_VALID, getEnteredValue());

            //                System.err.println("  silentlySetState returned: " + msg);
            legal = msg == null;
        }
    } else if (editor instanceof EnhancedCustomPropertyEditor) {
        Object entered = ((EnhancedCustomPropertyEditor) editor).getPropertyValue();

        try {
            editor.setValue(entered);
        } catch (IllegalStateException ise) {
            legal = false;
            msg = PropUtils.findLocalizedMessage(ise, entered, getProperty().getDisplayName());
        }
    }

    if (!legal && (msg == null)) {
        //            System.err.println(" not legal, constructing message");
        msg = NbBundle.getMessage(
                CustomEditorDisplayer.class, "FMT_CannotUpdateProperty",editor.getValue(), getProperty().getDisplayName()); //NOI18N
    }

    return msg;
}
 
/**
 * Convert the given text value using the given property editor.
 * @param oldValue the previous value, if available (may be {@code null})
 * @param newTextValue the proposed text value
 * @param editor the PropertyEditor to use
 * @return the converted value
 */
private Object doConvertTextValue(Object oldValue, String newTextValue, PropertyEditor editor) {
	try {
		editor.setValue(oldValue);
	}
	catch (Exception ex) {
		if (logger.isDebugEnabled()) {
			logger.debug("PropertyEditor [" + editor.getClass().getName() + "] does not support setValue call", ex);
		}
		// Swallow and proceed.
	}
	editor.setAsText(newTextValue);
	return editor.getValue();
}
 
源代码6 项目: spring4-understanding   文件: OptionTagTests.java
@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");
}
 
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();
}
 
源代码8 项目: lams   文件: TypeConverterDelegate.java
/**
 * Convert the given text value using the given property editor.
 * @param oldValue the previous value, if available (may be {@code null})
 * @param newTextValue the proposed text value
 * @param editor the PropertyEditor to use
 * @return the converted value
 */
private Object doConvertTextValue(Object oldValue, String newTextValue, PropertyEditor editor) {
	try {
		editor.setValue(oldValue);
	}
	catch (Exception ex) {
		if (logger.isDebugEnabled()) {
			logger.debug("PropertyEditor [" + editor.getClass().getName() + "] does not support setValue call", ex);
		}
		// Swallow and proceed.
	}
	editor.setAsText(newTextValue);
	return editor.getValue();
}
 
@Override
public Object convertValue(Object value, TypeDescriptor sourceType, TypeDescriptor targetType) {
	if (targetType.getType() == Void.class || targetType.getType() == Void.TYPE) {
		return null;
	}
	if (conversionService.canConvert(sourceType, targetType)) {
		return conversionService.convert(value, sourceType, targetType);
	}
	if (!String.class.isAssignableFrom(sourceType.getType())) {
		PropertyEditor editor = delegate.findCustomEditor(sourceType.getType(), null);
		editor.setValue(value);
		return editor.getAsText();
	}
	return delegate.convertIfNecessary(value, targetType.getType());
}
 
/**
 * Convert the given text value using the given property editor.
 * @param oldValue the previous value, if available (may be {@code null})
 * @param newTextValue the proposed text value
 * @param editor the PropertyEditor to use
 * @return the converted value
 */
private Object doConvertTextValue(@Nullable Object oldValue, String newTextValue, PropertyEditor editor) {
	try {
		editor.setValue(oldValue);
	}
	catch (Exception ex) {
		if (logger.isDebugEnabled()) {
			logger.debug("PropertyEditor [" + editor.getClass().getName() + "] does not support setValue call", ex);
		}
		// Swallow and proceed.
	}
	editor.setAsText(newTextValue);
	return editor.getValue();
}
 
@Override
public Object convertValue(Object value, TypeDescriptor sourceType, TypeDescriptor targetType) {
	if (targetType.getType() == Void.class || targetType.getType() == Void.TYPE) {
		return null;
	}
	if (conversionService.canConvert(sourceType, targetType)) {
		return conversionService.convert(value, sourceType, targetType);
	}
	if (!String.class.isAssignableFrom(sourceType.getType())) {
		PropertyEditor editor = delegate.findCustomEditor(sourceType.getType(), null);
		editor.setValue(value);
		return editor.getAsText();
	}
	return delegate.convertIfNecessary(value, targetType.getType());
}
 
源代码12 项目: spring4-understanding   文件: OptionTagTests.java
@Test
public void withCustomObjectAndEditorSelected() throws Exception {
	final PropertyEditor floatEditor = new SimpleFloatEditor();
	floatEditor.setValue(new Float("12.34"));
	String selectName = "testBean.someNumber";
	BindStatus bindStatus = new BindStatus(getRequestContext(), selectName, false) {
		@Override
		public PropertyEditor getEditor() {
			return floatEditor;
		}
	};
	getPageContext().setAttribute(SelectTag.LIST_VALUE_PAGE_ATTRIBUTE, bindStatus);

	this.tag.setValue(new Float(12.34));
	this.tag.setLabel("12.34f");

	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, "selected", "selected");
	assertBlockTagContains(output, "12.34f");
}
 
源代码13 项目: java-technology-stack   文件: DataBinderTests.java
@Test
public void testBindingWithFormatterAgainstFields() {
	TestBean tb = new TestBean();
	DataBinder binder = new DataBinder(tb);
	FormattingConversionService conversionService = new FormattingConversionService();
	DefaultConversionService.addDefaultConverters(conversionService);
	conversionService.addFormatterForFieldType(Float.class, new NumberStyleFormatter());
	binder.setConversionService(conversionService);
	binder.initDirectFieldAccess();
	MutablePropertyValues pvs = new MutablePropertyValues();
	pvs.add("myFloat", "1,2");

	LocaleContextHolder.setLocale(Locale.GERMAN);
	try {
		binder.bind(pvs);
		assertEquals(new Float(1.2), tb.getMyFloat());
		assertEquals("1,2", binder.getBindingResult().getFieldValue("myFloat"));

		PropertyEditor editor = binder.getBindingResult().findEditor("myFloat", Float.class);
		assertNotNull(editor);
		editor.setValue(new Float(1.4));
		assertEquals("1,4", editor.getAsText());

		editor = binder.getBindingResult().findEditor("myFloat", null);
		assertNotNull(editor);
		editor.setAsText("1,6");
		assertEquals(new Float(1.6), editor.getValue());
	}
	finally {
		LocaleContextHolder.resetLocaleContext();
	}
}
 
源代码14 项目: jdal   文件: SimpleTypeConverter.java
/**
 * {@inheritDoc}
 */
@SuppressWarnings("unchecked")
@Override
public <T> T convertIfNecessary(Object value, Class<T> requiredType, MethodParameter methodParam)
		throws TypeMismatchException {

	T convertedValue = null;
	try {
		convertedValue = super.convertIfNecessary(value, requiredType, methodParam);
	}
	catch (TypeMismatchException tme) {
		// Try Object to String conversion
		if (ClassUtils.isAssignable(String.class, requiredType)) {
			if (value != null) {
				PropertyEditor pe = findCustomEditor(value.getClass(), null);
				if (pe != null) {
					pe.setValue(value);
					return (T) pe.getAsText();
				}
				else {  // Object to String
					return (T) value.toString();
				}
			}
			else {  // null to String
				return (T) "";
			}
		}
		else {
			throw tme;
		}
	}

	return convertedValue;
}
 
源代码15 项目: spring4-understanding   文件: DataBinderTests.java
@Test
public void testBindingWithFormatter() {
	TestBean tb = new TestBean();
	DataBinder binder = new DataBinder(tb);
	FormattingConversionService conversionService = new FormattingConversionService();
	DefaultConversionService.addDefaultConverters(conversionService);
	conversionService.addFormatterForFieldType(Float.class, new NumberStyleFormatter());
	binder.setConversionService(conversionService);
	MutablePropertyValues pvs = new MutablePropertyValues();
	pvs.add("myFloat", "1,2");

	LocaleContextHolder.setLocale(Locale.GERMAN);
	try {
		binder.bind(pvs);
		assertEquals(new Float(1.2), tb.getMyFloat());
		assertEquals("1,2", binder.getBindingResult().getFieldValue("myFloat"));

		PropertyEditor editor = binder.getBindingResult().findEditor("myFloat", Float.class);
		assertNotNull(editor);
		editor.setValue(new Float(1.4));
		assertEquals("1,4", editor.getAsText());

		editor = binder.getBindingResult().findEditor("myFloat", null);
		assertNotNull(editor);
		editor.setAsText("1,6");
		assertEquals(new Float(1.6), editor.getValue());
	}
	finally {
		LocaleContextHolder.resetLocaleContext();
	}
}
 
源代码16 项目: java-technology-stack   文件: OptionTagTests.java
@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");
}
 
源代码17 项目: java-technology-stack   文件: OptionTagTests.java
@Test
public void withCustomObjectAndEditorSelected() throws Exception {
	final PropertyEditor floatEditor = new SimpleFloatEditor();
	floatEditor.setValue(new Float("12.34"));
	String selectName = "testBean.someNumber";
	BindStatus bindStatus = new BindStatus(getRequestContext(), selectName, false) {
		@Override
		public PropertyEditor getEditor() {
			return floatEditor;
		}
	};
	getPageContext().setAttribute(SelectTag.LIST_VALUE_PAGE_ATTRIBUTE, bindStatus);

	this.tag.setValue(new Float(12.34));
	this.tag.setLabel("12.34f");

	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, "selected", "selected");
	assertBlockTagContains(output, "12.34f");
}
 
源代码18 项目: blog_demos   文件: TypeConverterDelegate.java
/**
 * Convert the given text value using the given property editor.
 * @param oldValue the previous value, if available (may be {@code null})
 * @param newTextValue the proposed text value
 * @param editor the PropertyEditor to use
 * @return the converted value
 */
private Object doConvertTextValue(Object oldValue, String newTextValue, PropertyEditor editor) {
	try {
		editor.setValue(oldValue);
	}
	catch (Exception ex) {
		if (logger.isDebugEnabled()) {
			logger.debug("PropertyEditor [" + editor.getClass().getName() + "] does not support setValue call", ex);
		}
		// Swallow and proceed.
	}
	editor.setAsText(newTextValue);
	return editor.getValue();
}
 
protected AttributeList createMainAttributes( final Element element, final XmlWriter writer,
    final AttributeList attList ) {
  if ( element == null ) {
    throw new NullPointerException();
  }
  if ( writer == null ) {
    throw new NullPointerException();
  }
  if ( attList == null ) {
    throw new NullPointerException();
  }

  final ElementMetaData metaData = element.getElementType().getMetaData();
  final String[] attributeNamespaces = element.getAttributeNamespaces();
  for ( int i = 0; i < attributeNamespaces.length; i++ ) {
    final String namespace = attributeNamespaces[i];
    final String[] attributeNames = element.getAttributeNames( namespace );
    for ( int j = 0; j < attributeNames.length; j++ ) {
      final String name = attributeNames[j];
      final Object value = element.getAttribute( namespace, name );
      if ( value == null ) {
        continue;
      }

      final AttributeMetaData attrMeta = metaData.getAttributeDescription( namespace, name );
      if ( attrMeta == null ) {
        if ( value instanceof String ) {
          ensureNamespaceDefined( writer, attList, namespace );

          // preserve strings, but discard anything else. Until a attribute has a definition, we cannot
          // hope to understand the attribute's value. String-attributes can be expressed in XML easily,
          // and string is also how all unknown attributes are stored by the parser.
          attList.setAttribute( namespace, name, String.valueOf( value ) );
        }
        continue;
      }

      if ( attrMeta.isTransient() ) {
        continue;
      }
      if ( isFiltered( attrMeta ) ) {
        continue;
      }
      if ( attrMeta.isBulk() ) {
        continue;
      }

      ensureNamespaceDefined( writer, attList, namespace );
      try {
        final PropertyEditor propertyEditor = attrMeta.getEditor();
        if ( propertyEditor != null ) {
          propertyEditor.setValue( value );
          attList.setAttribute( namespace, name, propertyEditor.getAsText() );
        } else {
          final String attrValue = ConverterRegistry.toAttributeValue( value );
          attList.setAttribute( namespace, name, attrValue );
        }

      } catch ( BeanException e ) {
        AbstractElementWriteHandler.logger.warn( "Attribute '" + namespace + '|' + name
            + "' is not convertible with the bean-methods" );
      }
    }
  }
  return attList;
}
 
源代码20 项目: lams   文件: TypeConverterDelegate.java
/**
 * Convert the value to the required type (if necessary from a String),
 * using the given property editor.
 * @param oldValue the previous value, if available (may be {@code null})
 * @param newValue the proposed new value
 * @param requiredType the type we must convert to
 * (or {@code null} if not known, for example in case of a collection element)
 * @param editor the PropertyEditor to use
 * @return the new value, possibly the result of type conversion
 * @throws IllegalArgumentException if type conversion failed
 */
private Object doConvertValue(Object oldValue, Object newValue, Class<?> requiredType, PropertyEditor editor) {
	Object convertedValue = newValue;

	if (editor != 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 {
			editor.setValue(convertedValue);
			Object newConvertedValue = editor.getValue();
			if (newConvertedValue != convertedValue) {
				convertedValue = newConvertedValue;
				// Reset PropertyEditor: It already did a proper conversion.
				// Don't use it again for a setAsText call.
				editor = null;
			}
		}
		catch (Exception ex) {
			if (logger.isDebugEnabled()) {
				logger.debug("PropertyEditor [" + editor.getClass().getName() + "] does not support setValue call", ex);
			}
			// Swallow and proceed.
		}
	}

	Object returnValue = convertedValue;

	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.isTraceEnabled()) {
			logger.trace("Converting String array to comma-delimited String [" + convertedValue + "]");
		}
		convertedValue = StringUtils.arrayToCommaDelimitedString((String[]) convertedValue);
	}

	if (convertedValue instanceof String) {
		if (editor != null) {
			// Use PropertyEditor's setAsText in case of a String value.
			if (logger.isTraceEnabled()) {
				logger.trace("Converting String to [" + requiredType + "] using property editor [" + editor + "]");
			}
			String newTextValue = (String) convertedValue;
			return doConvertTextValue(oldValue, newTextValue, editor);
		}
		else if (String.class == requiredType) {
			returnValue = convertedValue;
		}
	}

	return returnValue;
}