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();
  }
Esempio n. 2
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());
      }
    }
  }
Esempio n. 3
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();
  }
  /**
   * 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;
    }
  }
Esempio n. 5
0
  @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;
  }
Esempio n. 6
0
  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());
    }
  }
Esempio n. 7
0
  @SuppressWarnings("rawtypes")
  private static MenuManager generateListEditorFor(
      final IMenuManager manager,
      final MenuManager subMenu,
      final PropertyDescriptor thisP,
      final Editable[] editables,
      final Layers theLayers,
      final Layer topLevelLayer) {

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

    // 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);
    }

    // retrieve the tags
    final String[] tags = pe.getTags();

    // are there any tags for this class?
    if (tags != null) {
      // create a drop-down list
      final MenuManager thisChoice = new MenuManager(thisP.getDisplayName());

      // sort out the setter details
      final Method getter = thisP.getReadMethod();

      // get the current value
      Object val = null;
      try {
        val = getter.invoke(editables[0], (Object[]) null);
      } catch (final Exception e) {
        MWC.Utilities.Errors.Trace.trace(e);
      }
      pe.setValue(val);

      // convert the current value to text
      final String currentValue = pe.getAsText();

      // and now a drop-down item for each options
      for (int j = 0; j < tags.length; j++) {
        final String thisTag = tags[j];
        pe.setAsText(thisTag);
        final Object thisValue = pe.getValue();

        // create the item
        final IAction thisA =
            new Action(thisTag, IAction.AS_RADIO_BUTTON) {
              public void run() {
                try {
                  // hey, since this is a radio button, we get two events when the
                  // selection changes - one for the value being unset, and the
                  // other
                  // for the value being set. So just fire for the new value (the
                  // one that's checked)
                  if (isChecked()) {
                    final Method setter = thisP.getWriteMethod();

                    // ok, place the change in the action
                    final ListPropertyAction la =
                        new ListPropertyAction(
                            thisP.getDisplayName(),
                            editables,
                            getter,
                            setter,
                            thisValue,
                            theLayers,
                            topLevelLayer);

                    // and add it to the history
                    CorePlugin.run(la);
                  }
                } catch (final Exception e) {
                  CorePlugin.logError(
                      IStatus.INFO, "While executing select editor for:" + thisP, e);
                }
              }
            };

        // is this the current one?
        if (thisTag.equals(currentValue)) {
          thisA.setChecked(true);
        }

        // add it to the menu
        thisChoice.add(thisA);
      }

      // is our sub-menu already created?
      if (result == null) {
        String nameStr;
        if (editables.length > 1) nameStr = MULTIPLE_ITEMS_STR;
        else nameStr = editables[0].getName();

        result = new MenuManager(nameStr);
        manager.add(result);
      }

      result.add(thisChoice);
    }

    return result;
  }
  @Test
  public void testPropertyEditor() throws Exception {

    // test
    Class<T> type = getType();
    PropertyEditor editor = finder.find(type);

    String[] inputData = getInputData();
    Object[] expectedData = getOutputData();
    String[] expectedStringData = getConvertedToText();
    try {
      assertTrue("Did not find property editor for type: " + type, editor != null);
      assertEquals(
          "Editor has wrong package!",
          this.getClass().getPackage(),
          editor.getClass().getPackage());
      logger.finest(
          "Found property editor for: " + type + ", editor=" + editor.getClass().getName());
      assertEquals(editor + " input length", inputData.length, expectedData.length);
    } catch (Exception e) {
      throw new RuntimeException(e);
    }

    for (int i = 0; i < inputData.length; i++) {
      String input = inputData[i];
      editor.setAsText(input);
      // TODO: check instance?
      T expected = (T) expectedData[i];
      T output = (T) editor.getValue();

      Comparator<T> c = getComparator();
      boolean equals = false;
      if (c == null) {
        equals = output != null ? output.equals(expected) : expected == null;
      } else {
        equals = c.compare(output, expected) == 0;
      }

      assertTrue(
          "Test at index '"
              + i
              + "'. Transform("
              + editor
              + ") of "
              + input
              + "\n does not equal! \nexpected = "
              + logT(expected)
              + "\noutput = "
              + logT(output),
          equals);

      String expectedStringOutput = expectedStringData[i];
      String stringOutput = editor.getAsText();
      logger.finest("setAsText '" + logString(input) + "'");
      logger.finest("getAsText '" + logString(stringOutput) + "'");
      if (type != Properties.class) {
        // We can't meaningfully compare the PropertiesEditor string output
        String msg =
            "Test at index '"
                + i
                + "'. PropertyEditor: "
                + editor.getClass().getName()
                + ", getAsText() == expectedStringOutput '";
        assertEquals(msg, expectedStringOutput, stringOutput);
      }
    }
  }