Exemple #1
1
  /**
   * Coerce the given object to targetType.
   *
   * @param value object to be coerced
   * @param targetType which should be object coerced into
   * @return the given value coerced to targetType
   */
  public static <T> T coerce(Object value, Class<T> targetType) {
    if (value == null) {
      return null;
    }

    if (targetType.isInstance(value)) {
      return targetType.cast(value);
    }

    if (value instanceof String) {
      PropertyEditor editor = PropertyEditorManager.findEditor(targetType);
      if (editor == null && Primitives.isWrapperType(targetType)) {
        editor = PropertyEditorManager.findEditor(Primitives.unwrap(targetType));
      }

      if (editor != null) {

        editor.setAsText((String) value);
        return targetType.cast(editor.getValue());
      } else if (targetType.isEnum()) {
        return targetType.cast(Enum.valueOf((Class<Enum>) targetType, (String) value));
      }
    }

    throw new IllegalArgumentException(
        MessageFormat.format(
            "Cannot convert {0} to object of {1} type", value, targetType.getName()));
  }
Exemple #2
0
  /**
   * Set the object to be edited.
   *
   * @param value The object to be edited.
   */
  public void setObject(Object value) {
    if (!(_type.isInstance(value))) {
      throw new IllegalArgumentException(value.getClass() + " is not of type " + _type);
    }
    _value = value;

    // Disable event generation.
    _squelchChangeEvents = true;

    // Iterate over each property, doing a lookup on the associated editor
    // and setting the editor's value to the value of the property.
    Iterator it = _prop2Editor.keySet().iterator();
    while (it.hasNext()) {
      PropertyDescriptor desc = (PropertyDescriptor) it.next();
      PropertyEditor editor = (PropertyEditor) _prop2Editor.get(desc);
      Method reader = desc.getReadMethod();
      if (reader != null) {
        try {
          Object val = reader.invoke(_value, null);
          editor.setValue(val);
        } catch (IllegalAccessException ex) {
          ex.printStackTrace();
        } catch (InvocationTargetException ex) {
          ex.getTargetException().printStackTrace();
        }
      }
    }

    // Enable event generation.
    _squelchChangeEvents = false;
  }
  public void testWithPropertyEditorStringComparison() 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 void testWithCustomObjectAndEditorSelected() 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("${myNumber}");
    this.tag.setLabel("${myNumber}");

    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");
  }
 /**
  * Checks for structured properties. Structured properties are properties with a name containg a
  * "_"
  *
  * @param propertyValues
  */
 @SuppressWarnings("unchecked")
 private void checkStructuredProperties(MutablePropertyValues propertyValues) {
   PropertyValue[] pvs = propertyValues.getPropertyValues();
   for (PropertyValue propertyValue : pvs) {
     if (!isStructured(propertyValue)) {
       continue;
     }
     String propertyName = getNameOf(propertyValue);
     Class<?> type = bean.getPropertyType(propertyName);
     if (type != null) {
       PropertyEditor editor = findCustomEditor(type, propertyName);
       if (null != editor && StructuredPropertyEditor.class.isAssignableFrom(editor.getClass())) {
         StructuredPropertyEditor structuredEditor = (StructuredPropertyEditor) editor;
         List fields = new ArrayList();
         fields.addAll(structuredEditor.getRequiredFields());
         fields.addAll(structuredEditor.getOptionalFields());
         Map<String, String> fieldValues = new HashMap<String, String>();
         try {
           for (Object fld : fields) {
             String field = (String) fld;
             PropertyValue partialStructValue =
                 propertyValues.getPropertyValue(
                     propertyName + STRUCTURED_PROPERTY_SEPERATOR + field);
             if (partialStructValue == null
                 && structuredEditor.getRequiredFields().contains(field)) {
               throw new MissingPropertyException(
                   "Required structured property is missing [" + field + "]");
             } else if (partialStructValue == null) {
               continue;
             }
             fieldValues.put(field, getStringValue(partialStructValue));
           }
           try {
             Object value = structuredEditor.assemble(type, fieldValues);
             for (Object fld : fields) {
               String field = (String) fld;
               PropertyValue partialStructValue =
                   propertyValues.getPropertyValue(
                       propertyName + STRUCTURED_PROPERTY_SEPERATOR + field);
               if (null != partialStructValue) {
                 partialStructValue.setConvertedValue(getStringValue(partialStructValue));
               }
             }
             propertyValues.addPropertyValue(new PropertyValue(propertyName, value));
           } catch (IllegalArgumentException iae) {
             LOG.warn(
                 "Unable to parse structured date from request for date [" + propertyName + "]",
                 iae);
           }
         } catch (InvalidPropertyException ipe) {
           // ignore
         }
       }
     }
   }
 }
  /**
   * 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;
  }
 /**
  * Convert a string value to its Object value.
  *
  * @param value - String value
  * @param prop - PropertyDescriptor
  * @return The object set to value (i.e. Integer). Will return String if no PropertyEditor is
  *     found.
  * @throws InstantiationException - Thrown on error getting the property editor from the property
  *     descriptor.
  * @throws IllegalAccessException - Thrown on error getting the property editor from the property
  *     descriptor.
  */
 protected Object convertValue(String value, PropertyDescriptor prop)
     throws InstantiationException, IllegalAccessException {
   PropertyEditor editor = getPropertyEditor(prop);
   Object obj = value;
   if (null != editor) {
     editor.setAsText(value);
     obj = editor.getValue();
   }
   return obj;
 }
  private static Object newValue(final Class<?> type, final String value) {
    final PropertyEditor editor = PropertyEditorFinder.getInstance().find(type);
    if (editor == null) {
      SarLogger.ROOT_LOGGER.propertyNotFound(type);
      return null;
    }
    editor.setAsText(value);

    return editor.getValue();
  }
  @SuppressWarnings({"rawtypes"})
  private EditorHelper findHelperFor(PropertyDescriptor prop, Editable subject) {
    EditorHelper res = null;

    // is there an explicit editor specified?
    Class specificEditor = prop.getPropertyEditorClass();

    // did we find one?
    if (specificEditor != null) {
      Object theEditor = null;
      try {
        theEditor = specificEditor.newInstance();
      } catch (Exception e) {
        CorePlugin.logError(Status.ERROR, "whilst finding helper", e);
      }

      if (theEditor instanceof java.beans.PropertyEditor) {
        final java.beans.PropertyEditor propEditor = (java.beans.PropertyEditor) theEditor;
        // ok. wrap it.
        if (!(propEditor instanceof DoNotUseTagEditorInPropertiesView)) {
          if (propEditor.getTags() != null) {
            // ok - do one of the combo-box editor types
            final String[] theTags = propEditor.getTags();
            res = new TagListHelper(theTags, propEditor);
          }
        }
      }
    }

    if (res == null) {

      // ok, find the type of object we're working with
      Class rawClass = EditableWrapper.getPropertyClass(_thisProp);

      for (Iterator iter = _myHelperList.iterator(); iter.hasNext(); ) {
        EditorHelper thisHelper = (EditorHelper) iter.next();
        if (thisHelper.editsThis(rawClass)) {
          res = thisHelper;
          break;
        }
      }

      if (res == null) {
        // ok, log the error
        String msg =
            "editor not found for:"
                + EditableWrapper.getPropertyClass(prop)
                + "("
                + prop.getDisplayName()
                + ")";
        System.out.println(msg);
      }
    }
    return res;
  }
 @SuppressWarnings("unchecked")
 protected <T> T convertValue(@Nullable Object value, @Nonnull Class<T> type) {
   if (value != null) {
     if (type.isAssignableFrom(value.getClass())) {
       return (T) value;
     } else {
       PropertyEditor editor = findEditor(type);
       editor.setValue(value);
       return (T) editor.getValue();
     }
   }
   return null;
 }
 /**
  * Convert the given text value using the given property editor.
  *
  * @param oldValue the previous value, if available (may be <code>null</code>)
  * @param newTextValue the proposed text value
  * @param editor the PropertyEditor to use
  * @return the converted value
  */
 protected 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();
 }
  public Element getElementServiceBindingValue(ServiceBinding binding, Element input) {
    if (input == null) throw new IllegalArgumentException("input cannot be null");

    PropertyEditor editor = PropertyEditorFinder.getInstance().find(Element.class);
    if (editor == null)
      throw new IllegalStateException("Cannot find PropertyEditor for type Element");

    editor.setValue(input);
    Reader reader = new StringReader(editor.getAsText());
    Writer writer = new StringWriter();

    doXslTransform(binding, getConfig(binding), reader, writer);

    editor.setAsText(writer.toString());
    return (Element) editor.getValue();
  }
Exemple #13
0
  /**
   * 将对象中的属性值置入到fields中。
   *
   * <p>对于<code>isValidated()</code>为<code>true</code>的group,该方法无效。
   */
  public void mapTo(Object object) {
    if (isValidated() || object == null) {
      return;
    }

    if (log.isDebugEnabled()) {
      log.debug(
          "Mapping properties to fields: group=\"{}\", object={}",
          getName(),
          ObjectUtil.identityToString(object));
    }

    BeanWrapper bean = new BeanWrapperImpl(object);
    getForm().getFormConfig().getPropertyEditorRegistrar().registerCustomEditors(bean);

    for (Field field : getFields()) {
      String propertyName = field.getFieldConfig().getPropertyName();

      if (bean.isReadableProperty(propertyName)) {
        Object propertyValue = bean.getPropertyValue(propertyName);
        Class<?> propertyType = bean.getPropertyType(propertyName);
        PropertyEditor editor = bean.findCustomEditor(propertyType, propertyName);

        if (editor == null) {
          editor = BeanUtils.findEditorByConvention(propertyType);
        }

        if (editor == null) {
          if (propertyType.isArray()
              || CollectionFactory.isApproximableCollectionType(propertyType)) {
            field.setValues((String[]) bean.convertIfNecessary(propertyValue, String[].class));
          } else {
            field.setValue(bean.convertIfNecessary(propertyValue, String.class));
          }
        } else {
          editor.setValue(propertyValue);
          field.setValue(editor.getAsText());
        }
      } else {
        log.debug(
            "No readable property \"{}\" found in type {}",
            propertyName,
            object.getClass().getName());
      }
    }
  }
 public static Object getValueFromBeanInfoPropertyEditor(
     Class<?> attrClass, String attrName, String attrValue, Class<?> propertyEditorClass)
     throws JasperException {
   try {
     PropertyEditor pe = (PropertyEditor) propertyEditorClass.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()));
   }
 }
 @Override
 public void actionPerformed(java.awt.event.ActionEvent e) {
   try {
     PropertyEditor propEd = property.getPropertyEditor();
     propEd.setValue(property.getValue());
     final Component custEditor = propEd.getCustomEditor();
     Object[] options = buttons();
     DialogDescriptor descriptor =
         new DialogDescriptor(
             custEditor,
             (String) getValue(Action.NAME),
             true,
             options,
             DialogDescriptor.CANCEL_OPTION,
             DialogDescriptor.DEFAULT_ALIGN,
             HelpCtx.DEFAULT_HELP,
             (ActionEvent e1) -> {
               try {
                 String action = e1.getActionCommand();
                 switch (action) {
                   case OK_COMMAND:
                     Object value = property.getPropertyEditor().getValue();
                     property.setValue(value);
                     break;
                   case RESTORE_COMMAND:
                     property.restoreDefaultValue();
                     break;
                 }
                 dialog.dispose();
               } catch (Exception ex) {
                 NotifyDescriptor descriptor2 =
                     new NotifyDescriptor.Message(
                         NbBundle.getMessage(PropertyAction.class, "MSG_InvalidValue")); // NOI18N
                 DialogDisplayer.getDefault().notify(descriptor2);
               }
             });
     descriptor.setClosingOptions(new Object[0]);
     dialog = DialogDisplayer.getDefault().createDialog(descriptor);
     dialog.setVisible(true);
     dialog = null;
   } catch (Exception ex) {
     ErrorManager.getDefault().notify(ex);
   }
 }
Exemple #16
0
  /**
   * Constructs a bean view that views the specified class.
   *
   * @param viewedClass the viewed class
   * @throws IntrospectionException if bean introspection fails
   * @see Introspector#getBeanInfo(Class)
   */
  public BeanForm(final Class<T> viewedClass) throws IntrospectionException {

    final GroupLayoutBuilder builder = new GroupLayoutBuilder(this);

    this.beanInfo = Introspector.getBeanInfo(viewedClass);
    for (final PropertyDescriptor pd : this.beanInfo.getPropertyDescriptors()) {
      final PropertyEditor editor = PropertyEditorManager.findEditor(pd.getPropertyType());
      if (editor == null) {
        continue;
      }
      final JTextField textField = new JTextField();
      textField.setEditable(false);
      textField.setText(editor.getAsText());
      this.fieldMap.put(pd.getName(), textField);
      builder.field(pd.getDisplayName(), textField);
    }

    builder.build();
  }
Exemple #17
0
    public void propertyChange(PropertyChangeEvent e) {
      if (_squelchChangeEvents) return;

      PropertyEditor editor = (PropertyEditor) e.getSource();
      PropertyDescriptor prop = (PropertyDescriptor) _editor2Prop.get(editor);
      Method writer = prop.getWriteMethod();
      if (writer != null) {
        try {
          Object[] params = {editor.getValue()};
          writer.invoke(_value, params);
          setObject(_value);
          firePropertyChange(_value, prop.getName(), null, editor.getValue());
        } catch (IllegalAccessException ex) {
          ex.printStackTrace();
        } catch (InvocationTargetException ex) {
          ex.getTargetException().printStackTrace();
        }
      }
    }
  /**
   * Wraps a property editor into a component.
   *
   * @param editor the editor to wrap
   * @return a button (if there is a custom editor), combo box (if the editor has tags), or text
   *     field (otherwise)
   */
  public Component getEditorComponent(final PropertyEditor editor) {
    String[] tags = editor.getTags();
    String text = editor.getAsText();
    if (editor.supportsCustomEditor()) {
      return editor.getCustomEditor();
    } else if (tags != null) {
      // make a combo box that shows all tags
      final JComboBox comboBox = new JComboBox(tags);
      comboBox.setSelectedItem(text);
      comboBox.addItemListener(
          new ItemListener() {
            public void itemStateChanged(ItemEvent event) {
              if (event.getStateChange() == ItemEvent.SELECTED)
                editor.setAsText((String) comboBox.getSelectedItem());
            }
          });
      return comboBox;
    } else {
      final JTextField textField = new JTextField(text, 10);
      textField
          .getDocument()
          .addDocumentListener(
              new DocumentListener() {
                public void insertUpdate(DocumentEvent e) {
                  try {
                    editor.setAsText(textField.getText());
                  } catch (IllegalArgumentException exception) {
                  }
                }

                public void removeUpdate(DocumentEvent e) {
                  try {
                    editor.setAsText(textField.getText());
                  } catch (IllegalArgumentException exception) {
                  }
                }

                public void changedUpdate(DocumentEvent e) {}
              });
      return textField;
    }
  }
 private static Object convert(TypeConverter typeConverter, Class<?> type, Object value)
     throws URISyntaxException, NoTypeConversionAvailableException {
   if (typeConverter != null) {
     return typeConverter.mandatoryConvertTo(type, value);
   }
   if (type == URI.class) {
     return new URI(value.toString());
   }
   PropertyEditor editor = PropertyEditorManager.findEditor(type);
   if (editor != null) {
     // property editor is not thread safe, so we need to lock
     Object answer;
     synchronized (LOCK) {
       editor.setAsText(value.toString());
       answer = editor.getValue();
     }
     return answer;
   }
   return null;
 }
 public static Object getValueFromPropertyEditorManager(
     Class<?> attrClass, String attrName, String attrValue) throws JasperException {
   try {
     PropertyEditor propEditor = PropertyEditorManager.findEditor(attrClass);
     if (propEditor != null) {
       propEditor.setAsText(attrValue);
       return propEditor.getValue();
     } else {
       throw new IllegalArgumentException(
           Localizer.getMessage("jsp.error.beans.propertyeditor.notregistered"));
     }
   } catch (IllegalArgumentException ex) {
     throw new JasperException(
         Localizer.getMessage(
             "jsp.error.beans.property.conversion",
             attrValue,
             attrClass.getName(),
             attrName,
             ex.getMessage()));
   }
 }
  public Object getValue(ServiceValueContext valueContext) throws Exception {
    MBeanAttributeInfo attributeInfo = valueContext.getAttributeInfo();
    ClassLoader cl = valueContext.getClassloader();

    String typeName = attributeInfo.getType();
    if (typeName == null)
      throw new DeploymentException(
          "AttributeInfo for " + attributeInfo.getName() + " has no type");

    // see if it is a primitive type first
    Class typeClass = Classes.getPrimitiveTypeForName(typeName);
    if (typeClass == null) {
      // nope try look up
      try {
        typeClass = cl.loadClass(typeName);
      } catch (ClassNotFoundException e) {
        throw new DeploymentException(
            "Class not found for attribute: " + attributeInfo.getName(), e);
      }
    }

    PropertyEditor editor = PropertyEditorFinder.getInstance().find(typeClass);
    if (editor == null)
      throw new DeploymentException(
          "No property editor for attribute: "
              + attributeInfo.getName()
              + "; type="
              + typeClass.getName());

    // JBAS-1709, temporarily switch the TCL so that property
    // editors have access to the actual deployment ClassLoader.
    ClassLoader tcl = Thread.currentThread().getContextClassLoader();
    Thread.currentThread().setContextClassLoader(cl);
    try {
      editor.setAsText(text);
      return editor.getValue();
    } finally {
      Thread.currentThread().setContextClassLoader(tcl);
    }
  }
  /**
   * can we edit this property with a drop-down list?
   *
   * @param thisP
   * @return yes/no
   */
  @SuppressWarnings("rawtypes")
  private static boolean supportsListEditor(final PropertyDescriptor thisP) {
    boolean res = false;

    // find out the type of the editor
    final Method m = thisP.getReadMethod();
    final Class cl = m.getReturnType();

    // is there a custom editor for this type?
    final Class c = thisP.getPropertyEditorClass();

    PropertyEditor pe = null;
    // try to create an editor for this class
    try {
      if (c != null) pe = (PropertyEditor) c.newInstance();
    } catch (final Exception e) {
      MWC.Utilities.Errors.Trace.trace(e);
    }

    // did it work?
    if (pe == null) {
      // try to find an editor for this through our manager
      pe = PropertyEditorManager.findEditor(cl);
    }

    // have we managed to create an editor?
    if (pe != null) {
      // retrieve the tags
      final String[] tags = pe.getTags();

      // are there any tags for this class?
      if (tags != null) {
        res = true;
      }
    }

    return res;
  }
  @Override
  protected final int doStartTagInternal() throws JspException {
    if (this.value != null) {
      // Find the containing EditorAwareTag (e.g. BindTag), if applicable.
      EditorAwareTag tag =
          (EditorAwareTag) TagSupport.findAncestorWithClass(this, EditorAwareTag.class);
      if (tag == null) {
        throw new JspException(
            "TransformTag can only be used within EditorAwareTag (e.g. BindTag)");
      }

      // OK, let's obtain the editor...
      String result = null;
      PropertyEditor editor = tag.getEditor();
      if (editor != null) {
        // If an editor was found, edit the value.
        editor.setValue(this.value);
        result = editor.getAsText();
      } else {
        // Else, just do a toString.
        result = this.value.toString();
      }
      result = htmlEscape(result);
      if (this.var != null) {
        pageContext.setAttribute(this.var, result, TagUtils.getScope(this.scope));
      } else {
        try {
          // Else, just print it out.
          pageContext.getOut().print(result);
        } catch (IOException ex) {
          throw new JspException(ex);
        }
      }
    }

    return SKIP_BODY;
  }
Exemple #24
0
 /**
  * Configures the given component by setting the value for the appropriate config option.
  *
  * @param component the component to be configured
  * @param configName the name of the config option
  * @param configValue the value of the config option
  */
 @Deprecated
 public static <T> void configure(Component component, String configName, T configValue) {
   List<Field> fields = getAllFields(component);
   for (Field f : fields) {
     ConfigOption option = f.getAnnotation(ConfigOption.class);
     if (option != null) {
       if (option.name().equals(configName)) {
         try {
           PropertyEditor editor = PropertyEditor.class.newInstance();
           editor.setAsText(configValue.toString());
           Method method =
               component
                   .getClass()
                   .getMethod(
                       "set"
                           + Character.toUpperCase(f.getName().charAt(0))
                           + f.getName().substring(1),
                       getClassForObject(editor.getValue()));
           method.invoke(component, editor.getValue());
         } catch (IllegalArgumentException e) {
           e.printStackTrace();
         } catch (InstantiationException e) {
           e.printStackTrace();
         } catch (IllegalAccessException e) {
           e.printStackTrace();
         } catch (InvocationTargetException e) {
           e.printStackTrace();
         } catch (SecurityException e) {
           e.printStackTrace();
         } catch (NoSuchMethodException e) {
           e.printStackTrace();
         }
       }
     }
   }
 }
  /**
   * Convert the value to the required type (if necessary from a String), for the specified
   * property.
   *
   * @param propertyName name of the property
   * @param oldValue the previous value, if available (may be <code>null</code>)
   * @param newValue the proposed new value
   * @param requiredType the type we must convert to (or <code>null</code> if not known, for example
   *     in case of a collection element)
   * @param typeDescriptor the descriptor for the target property or field
   * @return the new value, possibly the result of type conversion
   * @throws IllegalArgumentException if type conversion failed
   */
  @SuppressWarnings("unchecked")
  public <T> T convertIfNecessary(
      String propertyName,
      Object oldValue,
      Object newValue,
      Class<T> requiredType,
      TypeDescriptor typeDescriptor)
      throws IllegalArgumentException {

    Object convertedValue = newValue;

    // Custom editor for this type?
    PropertyEditor editor =
        this.propertyEditorRegistry.findCustomEditor(requiredType, propertyName);

    // No custom editor but custom ConversionService specified?
    ConversionService conversionService = this.propertyEditorRegistry.getConversionService();
    if (editor == null && conversionService != null && convertedValue != null) {
      TypeDescriptor sourceTypeDesc = TypeDescriptor.forObject(convertedValue);
      TypeDescriptor targetTypeDesc = typeDescriptor.forElementType(requiredType);
      if (conversionService.canConvert(sourceTypeDesc, targetTypeDesc)) {
        return (T) conversionService.convert(convertedValue, sourceTypeDesc, targetTypeDesc);
      }
    }

    // Value not of required type?
    if (editor != null
        || (requiredType != null && !ClassUtils.isAssignableValue(requiredType, convertedValue))) {
      if (requiredType != null
          && Collection.class.isAssignableFrom(requiredType)
          && convertedValue instanceof String
          && typeDescriptor.getMethodParameter() != null) {
        Class elemType =
            GenericCollectionTypeResolver.getCollectionParameterType(
                typeDescriptor.getMethodParameter());
        if (elemType != null && Enum.class.isAssignableFrom(elemType)) {
          convertedValue = StringUtils.commaDelimitedListToStringArray((String) convertedValue);
        }
      }
      if (editor == null) {
        editor = findDefaultEditor(requiredType, typeDescriptor);
      }
      convertedValue = doConvertValue(oldValue, convertedValue, requiredType, editor);
    }

    if (requiredType != null) {
      // Try to apply some standard type conversion rules if appropriate.

      if (convertedValue != null) {
        if (requiredType.isArray()) {
          // Array required -> apply appropriate conversion of elements.
          if (convertedValue instanceof String
              && Enum.class.isAssignableFrom(requiredType.getComponentType())) {
            convertedValue = StringUtils.commaDelimitedListToStringArray((String) convertedValue);
          }
          return (T)
              convertToTypedArray(convertedValue, propertyName, requiredType.getComponentType());
        } else if (convertedValue instanceof Collection) {
          // Convert elements to target type, if determined.
          convertedValue =
              convertToTypedCollection(
                  (Collection) convertedValue, propertyName, requiredType, typeDescriptor);
        } else if (convertedValue instanceof Map) {
          // Convert keys and values to respective target type, if determined.
          convertedValue =
              convertToTypedMap((Map) convertedValue, propertyName, requiredType, typeDescriptor);
        }
        if (convertedValue.getClass().isArray() && Array.getLength(convertedValue) == 1) {
          convertedValue = Array.get(convertedValue, 0);
        }
        if (String.class.equals(requiredType)
            && ClassUtils.isPrimitiveOrWrapper(convertedValue.getClass())) {
          // We can stringify any primitive value...
          return (T) convertedValue.toString();
        } else if (convertedValue instanceof String && !requiredType.isInstance(convertedValue)) {
          if (!requiredType.isInterface() && !requiredType.isEnum()) {
            try {
              Constructor strCtor = requiredType.getConstructor(String.class);
              return (T) BeanUtils.instantiateClass(strCtor, convertedValue);
            } catch (NoSuchMethodException ex) {
              // proceed with field lookup
              if (logger.isTraceEnabled()) {
                logger.trace(
                    "No String constructor found on type [" + requiredType.getName() + "]", ex);
              }
            } catch (Exception ex) {
              if (logger.isDebugEnabled()) {
                logger.debug(
                    "Construction via String failed for type [" + requiredType.getName() + "]", ex);
              }
            }
          }
          String trimmedValue = ((String) convertedValue).trim();
          if (requiredType.isEnum() && "".equals(trimmedValue)) {
            // It's an empty enum identifier: reset the enum value to null.
            return null;
          }

          convertedValue = attemptToConvertStringToEnum(requiredType, trimmedValue, convertedValue);
        }
      }

      if (!ClassUtils.isAssignableValue(requiredType, convertedValue)) {
        // Definitely doesn't match: throw IllegalArgumentException/IllegalStateException
        StringBuilder msg = new StringBuilder();
        msg.append("Cannot convert value of type [")
            .append(ClassUtils.getDescriptiveType(newValue));
        msg.append("] to required type [")
            .append(ClassUtils.getQualifiedName(requiredType))
            .append("]");
        if (propertyName != null) {
          msg.append(" for property '").append(propertyName).append("'");
        }
        if (editor != null) {
          msg.append(": PropertyEditor [")
              .append(editor.getClass().getName())
              .append("] returned inappropriate value");
          throw new IllegalArgumentException(msg.toString());
        } else {
          msg.append(": no matching editors or conversion strategy found");
          throw new IllegalStateException(msg.toString());
        }
      }
    }

    return (T) convertedValue;
  }
  public Reference createReference(Object bean) throws NamingException {
    try {
      BeanInfo bi = Introspector.getBeanInfo(bean.getClass());
      PropertyDescriptor[] pds = bi.getPropertyDescriptors();
      List refAddrs = new ArrayList();
      String factoryClassLocation = defaultFactoryClassLocation;

      boolean using_ref_props = referenceProperties.size() > 0;

      // we only include this so that on dereference we are not surprised to find some properties
      // missing
      if (using_ref_props)
        refAddrs.add(
            new BinaryRefAddr(REF_PROPS_KEY, SerializableUtils.toByteArray(referenceProperties)));

      for (int i = 0, len = pds.length; i < len; ++i) {
        PropertyDescriptor pd = pds[i];
        String propertyName = pd.getName();
        // System.err.println("Making Reference: " + propertyName);

        if (using_ref_props && !referenceProperties.contains(propertyName)) {
          // System.err.println("Not a ref_prop -- continuing.");
          continue;
        }

        Class propertyType = pd.getPropertyType();
        Method getter = pd.getReadMethod();
        Method setter = pd.getWriteMethod();
        if (getter != null
            && setter != null) // only use properties that are both readable and writable
        {
          Object val = getter.invoke(bean, EMPTY_ARGS);
          // System.err.println( "val: " + val );
          if (propertyName.equals("factoryClassLocation")) {
            if (String.class != propertyType)
              throw new NamingException(
                  this.getClass().getName()
                      + " requires a factoryClassLocation property to be a string, "
                      + propertyType.getName()
                      + " is not valid.");
            factoryClassLocation = (String) val;
          }

          if (val == null) {
            RefAddr addMe = new BinaryRefAddr(propertyName, NULL_TOKEN_BYTES);
            refAddrs.add(addMe);
          } else if (Coerce.canCoerce(propertyType)) {
            RefAddr addMe = new StringRefAddr(propertyName, String.valueOf(val));
            refAddrs.add(addMe);
          } else // other Object properties
          {
            RefAddr addMe = null;
            PropertyEditor pe = BeansUtils.findPropertyEditor(pd);
            if (pe != null) {
              pe.setValue(val);
              String textValue = pe.getAsText();
              if (textValue != null) addMe = new StringRefAddr(propertyName, textValue);
            }
            if (addMe == null) // property editor approach failed
            addMe =
                  new BinaryRefAddr(
                      propertyName,
                      SerializableUtils.toByteArray(
                          val, indirector, IndirectPolicy.INDIRECT_ON_EXCEPTION));
            refAddrs.add(addMe);
          }
        } else {
          // 				System.err.println(this.getClass().getName() +
          // 						   ": Skipping " + propertyName + " because it is " + (setter == null ?
          // "read-only." : "write-only."));

          if (logger.isLoggable(MLevel.WARNING))
            logger.warning(
                this.getClass().getName()
                    + ": Skipping "
                    + propertyName
                    + " because it is "
                    + (setter == null ? "read-only." : "write-only."));
        }
      }
      Reference out =
          new Reference(bean.getClass().getName(), factoryClassName, factoryClassLocation);
      for (Iterator ii = refAddrs.iterator(); ii.hasNext(); ) out.add((RefAddr) ii.next());
      return out;
    } catch (Exception e) {
      // e.printStackTrace();
      if (Debug.DEBUG && logger.isLoggable(MLevel.FINE))
        logger.log(MLevel.FINE, "Exception trying to create Reference.", e);

      throw new NamingException("Could not create reference from bean: " + e.toString());
    }
  }
Exemple #27
0
  protected void getBeanElementProperties(Element element, Object bean, PropertyDescriptor pd)
      throws IntrospectionException, IllegalAccessException {
    Element propertyElement = null;
    Class classOfProperty = pd.getPropertyType();
    Object[] argsNone = {};
    // If the property is "class" and the type is java.lang.Class.class then
    // this is the class of the bean, which we've already encoded.
    // In this special case, return null.
    if (!((pd.getName().charAt(0) == 'c') && pd.getName().equals("class"))
        && !classOfProperty.equals(java.lang.Class.class)) {
      // Don't process property if it is in the list of fields to be ignored
      boolean omittedField = false;
      try {
        Field field = bean.getClass().getDeclaredField(pd.getName());
        omittedField = field.isAnnotationPresent(ObjectXmlOmitField.class);
      } catch (NoSuchFieldException nsfe) {
      }
      if (!omittedField) {
        String propertyName = formatName(pd.getName());
        // Hereafter, we're trying to create a representation of the property
        // based on the property's value.
        // The very first thing we need to do is get the value of the
        // property as an object. If we can't do that, we can't get any
        // representation of the property at all.
        Object propertyValue = null;
        try {
          Method getter = pd.getReadMethod();
          if (getter != null) {
            propertyValue = getter.invoke(bean, argsNone);
          }
        } catch (Exception ex) {
          // couldn't get value
          System.err.println(ex.getMessage());
        }
        // See if this property's value is something we can represent as a
        // standard data type that can be converted to an xsd type,
        // or if it's something that must be represented as a JavaBean.
        if (propertyElement == null) {

          PropertyEditor propEditor = PropertyEditorManager.findEditor(classOfProperty);
          // If the property editor is not null, pass the property's
          // value to the PropertyEditor, and then ask the PropertyEditor
          // for the object and then attempt to convert it to a standard type.

          if ((propEditor != null)
              || (classOfProperty == java.util.Calendar.class)
              || (classOfProperty == java.util.Date.class)) {
            // The object is a standard type
            // (e.g. a wrapper around a primitive type, a String, or a Date or Calendar object)
            try {
              Object object;
              if ((classOfProperty == java.util.Calendar.class)
                  || (classOfProperty == java.util.Date.class)) object = propertyValue;
              else {
                propEditor.setValue(propertyValue);
                object = propEditor.getValue();
              }
              Element childElement = getStandardObjectElement(document, object, propertyName);
              if (includeNullValues
                  || !childElement
                      .getAttribute(
                          NamespaceConstants.NSPREFIX_SCHEMA_XSI
                              + ":"
                              + org.apache.axis.Constants.ATTR_TYPE)
                      .equals("anyType")) {
                if (!includeTypeInfo) {
                  childElement.removeAttribute(
                      NamespaceConstants.NSPREFIX_SCHEMA_XSI
                          + ":"
                          + org.apache.axis.Constants.ATTR_TYPE);
                  childElement.removeAttribute(NamespaceConstants.NSPREFIX_SCHEMA_XSI + ":null");
                }
                try {
                  Field field = bean.getClass().getDeclaredField(propertyName);
                  if (field.isAnnotationPresent(ObjectXmlAsAttribute.class)) {
                    String attrName = null;
                    if (includeTypeInfo) attrName = nsPrefix + ":" + propertyName;
                    else attrName = propertyName;
                    element.setAttribute(attrName, childElement.getFirstChild().getNodeValue());
                  } else if (field.isAnnotationPresent(ObjectXmlAsValue.class))
                    element.setTextContent(childElement.getFirstChild().getNodeValue());
                  else element.appendChild(childElement);
                } catch (NoSuchFieldException nfse) {
                  element.appendChild(childElement);
                }
              }
            } catch (Exception e) {
            }
          } else {
            // The object is not an XSD-encoded datatype, it must be a JavaBean
            try {
              String propertyTypeName = null;
              if (propertyValue != null) {
                // get object type
                Class propertyType = pd.getPropertyType();
                propertyTypeName = propertyType.getName();
              }
              getBeanElements(element, propertyName, propertyTypeName, propertyValue);
            } catch (Exception e) {
            }
          }
        }
      }
    }
  }
 public static PropertyAction createIfEditable(RADProperty<?> property) {
   PropertyEditor propEd = property.getPropertyEditor();
   return propEd != null && propEd.supportsCustomEditor() ? new PropertyAction(property) : null;
 }
Exemple #29
0
  /**
   * Standard constructor.
   *
   * @param type Type that you are going to be creating and editor for.
   * @param readOnly Set to true to create a read-only customizer.
   */
  public DynamicCustomizer(Class type, boolean readOnly) {
    super(new GridBagLayout());
    _readOnly = readOnly;
    _type = type;

    LabelFieldGBC gbc = new LabelFieldGBC();
    try {
      BeanInfo info = Introspector.getBeanInfo(type);
      // Set up pretty display stuff.
      setBorder(BorderFactory.createTitledBorder(info.getBeanDescriptor().getDisplayName()));
      setToolTipText(info.getBeanDescriptor().getShortDescription());

      // Get the properties and sort them.
      PropertyDescriptor[] props = info.getPropertyDescriptors();
      Arrays.sort(props, new PropertyComparator());
      for (int i = 0; i < props.length; i++) {
        // Ignore the "class" property, if it is provided.
        if (props[i].getName().equals("class")) continue;
        // Create a label for the field.
        JLabel label = new JLabel(props[i].getDisplayName() + ":");

        // Lookup the editor.
        PropertyEditor editor = getEditorForProperty(props[i]);

        // Add a listener to the editor so we know when to update
        // the bean's fields.
        editor.addPropertyChangeListener(_eListener);

        // XXX What we need to do right here is provide a component
        // that makes use of the "paintable" capability of the editor.
        Component comp = editor.getCustomEditor();
        if (comp == null) {
          comp = new JLabel("<No editor available.>");
          ((JLabel) comp).setBorder(BorderFactory.createEtchedBorder());
        }

        // See if it is a read-only property. If so, then just
        // display it.
        if (_readOnly || props[i].getWriteMethod() == null) {
          comp.setEnabled(false);
        }

        // Setup the accellerator key.
        label.setLabelFor(comp);
        label.setDisplayedMnemonic(label.getText().charAt(0));

        // Set the tool tip text, if any.
        String tip = props[i].getShortDescription();
        if (tip != null) {
          label.setToolTipText(tip);
          if (comp instanceof JComponent) {
            ((JComponent) comp).setToolTipText(tip);
          }
        }

        // Add the label and fields.
        add(label, gbc.forLabel());
        add(comp, gbc.forField());

        // Set the mappings between editor and property, etc. for
        // quick lookup later.
        _prop2Editor.put(props[i], editor);
        _editor2Prop.put(editor, props[i]);
      }
      // Filler...
      add(new JLabel(), gbc.forLastLabel());

    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }
  /**
   * Convert the value to the required type (if necessary from a String), for the specified
   * property.
   *
   * @param propertyName name of the property
   * @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 typeDescriptor the descriptor for the target property or field
   * @return the new value, possibly the result of type conversion
   * @throws IllegalArgumentException if type conversion failed
   */
  @SuppressWarnings("unchecked")
  public <T> T convertIfNecessary(
      String propertyName,
      Object oldValue,
      Object newValue,
      Class<T> requiredType,
      TypeDescriptor typeDescriptor)
      throws IllegalArgumentException {

    // Custom editor for this type?
    PropertyEditor editor =
        this.propertyEditorRegistry.findCustomEditor(requiredType, propertyName);

    ConversionFailedException conversionAttemptEx = null;

    // No custom editor but custom ConversionService specified?
    ConversionService conversionService = this.propertyEditorRegistry.getConversionService();
    if (editor == null && conversionService != null && newValue != null && typeDescriptor != null) {
      TypeDescriptor sourceTypeDesc = TypeDescriptor.forObject(newValue);
      if (conversionService.canConvert(sourceTypeDesc, typeDescriptor)) {
        try {
          return (T) conversionService.convert(newValue, sourceTypeDesc, typeDescriptor);
        } catch (ConversionFailedException ex) {
          // fallback to default conversion logic below
          conversionAttemptEx = ex;
        }
      }
    }

    Object convertedValue = newValue;

    // Value not of required type?
    if (editor != null
        || (requiredType != null && !ClassUtils.isAssignableValue(requiredType, convertedValue))) {
      if (typeDescriptor != null
          && requiredType != null
          && Collection.class.isAssignableFrom(requiredType)
          && convertedValue instanceof String) {
        TypeDescriptor elementTypeDesc = typeDescriptor.getElementTypeDescriptor();
        if (elementTypeDesc != null) {
          Class<?> elementType = elementTypeDesc.getType();
          if (Class.class == elementType || Enum.class.isAssignableFrom(elementType)) {
            convertedValue = StringUtils.commaDelimitedListToStringArray((String) convertedValue);
          }
        }
      }
      if (editor == null) {
        editor = findDefaultEditor(requiredType);
      }
      convertedValue = doConvertValue(oldValue, convertedValue, requiredType, editor);
    }

    boolean standardConversion = false;

    if (requiredType != null) {
      // Try to apply some standard type conversion rules if appropriate.

      if (convertedValue != null) {
        if (Object.class == requiredType) {
          return (T) convertedValue;
        } else if (requiredType.isArray()) {
          // Array required -> apply appropriate conversion of elements.
          if (convertedValue instanceof String
              && Enum.class.isAssignableFrom(requiredType.getComponentType())) {
            convertedValue = StringUtils.commaDelimitedListToStringArray((String) convertedValue);
          }
          return (T)
              convertToTypedArray(convertedValue, propertyName, requiredType.getComponentType());
        } else if (convertedValue instanceof Collection) {
          // Convert elements to target type, if determined.
          convertedValue =
              convertToTypedCollection(
                  (Collection<?>) convertedValue, propertyName, requiredType, typeDescriptor);
          standardConversion = true;
        } else if (convertedValue instanceof Map) {
          // Convert keys and values to respective target type, if determined.
          convertedValue =
              convertToTypedMap(
                  (Map<?, ?>) convertedValue, propertyName, requiredType, typeDescriptor);
          standardConversion = true;
        }
        if (convertedValue.getClass().isArray() && Array.getLength(convertedValue) == 1) {
          convertedValue = Array.get(convertedValue, 0);
          standardConversion = true;
        }
        if (String.class == requiredType
            && ClassUtils.isPrimitiveOrWrapper(convertedValue.getClass())) {
          // We can stringify any primitive value...
          return (T) convertedValue.toString();
        } else if (convertedValue instanceof String && !requiredType.isInstance(convertedValue)) {
          if (conversionAttemptEx == null
              && !requiredType.isInterface()
              && !requiredType.isEnum()) {
            try {
              Constructor<T> strCtor = requiredType.getConstructor(String.class);
              return BeanUtils.instantiateClass(strCtor, convertedValue);
            } catch (NoSuchMethodException ex) {
              // proceed with field lookup
              if (logger.isTraceEnabled()) {
                logger.trace(
                    "No String constructor found on type [" + requiredType.getName() + "]", ex);
              }
            } catch (Exception ex) {
              if (logger.isDebugEnabled()) {
                logger.debug(
                    "Construction via String failed for type [" + requiredType.getName() + "]", ex);
              }
            }
          }
          String trimmedValue = ((String) convertedValue).trim();
          if (requiredType.isEnum() && "".equals(trimmedValue)) {
            // It's an empty enum identifier: reset the enum value to null.
            return null;
          }
          convertedValue = attemptToConvertStringToEnum(requiredType, trimmedValue, convertedValue);
          standardConversion = true;
        } else if (convertedValue instanceof Number
            && Number.class.isAssignableFrom(requiredType)) {
          convertedValue =
              NumberUtils.convertNumberToTargetClass(
                  (Number) convertedValue, (Class<Number>) requiredType);
          standardConversion = true;
        }
      } else {
        // convertedValue == null
        if (requiredType == Optional.class) {
          convertedValue = Optional.empty();
        }
      }

      if (!ClassUtils.isAssignableValue(requiredType, convertedValue)) {
        if (conversionAttemptEx != null) {
          // Original exception from former ConversionService call above...
          throw conversionAttemptEx;
        } else if (conversionService != null) {
          // ConversionService not tried before, probably custom editor found
          // but editor couldn't produce the required type...
          TypeDescriptor sourceTypeDesc = TypeDescriptor.forObject(newValue);
          if (conversionService.canConvert(sourceTypeDesc, typeDescriptor)) {
            return (T) conversionService.convert(newValue, sourceTypeDesc, typeDescriptor);
          }
        }

        // Definitely doesn't match: throw IllegalArgumentException/IllegalStateException
        StringBuilder msg = new StringBuilder();
        msg.append("Cannot convert value of type '")
            .append(ClassUtils.getDescriptiveType(newValue));
        msg.append("' to required type '")
            .append(ClassUtils.getQualifiedName(requiredType))
            .append("'");
        if (propertyName != null) {
          msg.append(" for property '").append(propertyName).append("'");
        }
        if (editor != null) {
          msg.append(": PropertyEditor [")
              .append(editor.getClass().getName())
              .append("] returned inappropriate value of type '")
              .append(ClassUtils.getDescriptiveType(convertedValue))
              .append("'");
          throw new IllegalArgumentException(msg.toString());
        } else {
          msg.append(": no matching editors or conversion strategy found");
          throw new IllegalStateException(msg.toString());
        }
      }
    }

    if (conversionAttemptEx != null) {
      if (editor == null
          && !standardConversion
          && requiredType != null
          && Object.class != requiredType) {
        throw conversionAttemptEx;
      }
      logger.debug(
          "Original ConversionService attempt failed - ignored since "
              + "PropertyEditor based conversion eventually succeeded",
          conversionAttemptEx);
    }

    return (T) convertedValue;
  }