Пример #1
0
  /**
   * Using the Java Introspector class the method returns the property descriptors obtained through
   * introspection.
   *
   * @param clazz to introspect
   * @return array of property descriptors
   */
  protected static PropertyDescriptor[] introspect(Class clazz) {
    BeanInfo beanInfo;

    try {
      beanInfo = Introspector.getBeanInfo(clazz);
    } catch (IntrospectionException e) {
      return (new PropertyDescriptor[0]);
    }

    return beanInfo.getPropertyDescriptors();
  }
Пример #2
0
 public Bean(String classPackage, String clazz, ClassLoaderStrategy cls, Bean topLevelBean)
     throws Exception {
   // Get the no-arg constructor and create the bean
   try {
     Class classOfBean = ObjectXml.getClassOfBean((ClassLoader) cls, classPackage + "." + clazz);
     Constructor ct = null;
     // check whether this class is an inner class
     if (classOfBean.getEnclosingClass() != null) {
       ct = classOfBean.getConstructor(new Class[] {classOfBean.getEnclosingClass()});
       beanObject = ct.newInstance(new Object[] {topLevelBean.getBeanObject()});
     } else {
       ct = classOfBean.getConstructor((Class[]) null);
       beanObject = ct.newInstance((Object[]) null);
     }
     // Get an array of property descriptors
     beanInfo = Introspector.getBeanInfo(classOfBean);
     PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();
     // load property descriptors into hashtable
     propDesc = new Properties();
     for (int i = 0; i < pds.length; i++) {
       propDesc.put(pds[i].getName(), pds[i]);
     }
   } catch (Exception e) {
     System.err.println("Exception creating bean: " + e.getMessage());
     e.printStackTrace();
     throw e;
   }
 }
Пример #3
0
  /**
   * Reads the children of an XML element and matches them to properties of a bean.
   *
   * @param ob The bean to receive the values
   * @param element The element the corresponds to the bean
   * @throws IOException If there is an error reading the document
   */
  public void readObject(Object ob, Element element) throws IOException {
    // If the object is null, skip the element
    if (ob == null) {
      return;
    }

    try {
      BeanInfo info = (BeanInfo) beanCache.get(ob.getClass());

      if (info == null) {
        // Get the bean info for the object
        info = Introspector.getBeanInfo(ob.getClass(), Object.class);

        beanCache.put(ob.getClass(), info);
      }

      // Get the object's properties
      PropertyDescriptor[] props = info.getPropertyDescriptors();

      // Get the attributes of the node
      NamedNodeMap attrs = element.getAttributes();

      // Get the children of the XML element
      NodeList nodes = element.getChildNodes();

      int numNodes = nodes.getLength();

      for (int i = 0; i < props.length; i++) {
        // Treat indexed properties a little differently
        if (props[i] instanceof IndexedPropertyDescriptor) {
          readIndexedProperty(ob, (IndexedPropertyDescriptor) props[i], nodes, attrs);
        } else {
          readProperty(ob, props[i], nodes, attrs);
        }
      }
    } catch (IntrospectionException exc) {
      throw new IOException(
          "Error getting bean info for " + ob.getClass().getName() + ": " + exc.toString());
    }
  }
Пример #4
0
  /* PROTECTED METHODS */
  protected void getBeanElements(
      Element parentElement, String objectName, String objectType, Object bean)
      throws IntrospectionException, IllegalAccessException {
    if (objectName == null) {
      // Get just the class name by lopping off the package name
      StringBuffer sb = new StringBuffer(bean.getClass().getName());
      sb.delete(0, sb.lastIndexOf(".") + 1);
      objectName = sb.toString();
    }

    // Check if the bean is a standard Java object type or a byte[] (encoded as a base 64 array)
    Element element = getStandardObjectElement(document, bean, objectName);
    // If the body element object is null then the bean is not a standard Java object type
    if (element != null) {
      if (includeNullValues
          || !element
              .getAttribute(
                  NamespaceConstants.NSPREFIX_SCHEMA_XSI
                      + ":"
                      + org.apache.axis.Constants.ATTR_TYPE)
              .equals("anyType")) {
        if (!includeTypeInfo) {
          element.removeAttribute(
              NamespaceConstants.NSPREFIX_SCHEMA_XSI + ":" + org.apache.axis.Constants.ATTR_TYPE);
          element.removeAttribute(NamespaceConstants.NSPREFIX_SCHEMA_XSI + ":null");
        }
        parentElement.appendChild(element);
      }
    } else {
      // Analyze the bean
      Class classOfBean = null;
      if (bean != null) classOfBean = bean.getClass();
      // If the object is an array, then serialize each of the beans in the array.
      if ((classOfBean != null) && (classOfBean.isArray())) {
        String[] arrayInfo = getXsdSoapArrayInfo(classOfBean.getCanonicalName(), nsPrefix);
        int arrayLen = Array.getLength(bean);
        StringBuffer arrayType = new StringBuffer(arrayInfo[1]);
        arrayType.insert(arrayType.indexOf("[]") + 1, arrayLen);
        if (objectName.charAt(objectName.length() - 1) == ';')
          objectName =
              new StringBuffer(objectName).deleteCharAt(objectName.length() - 1).toString();
        element = document.createElement(objectName);
        parentElement.appendChild(element);
        // Get the bean objects from the array and serialize each
        for (int i = 0; i < arrayLen; i++) {
          Object b = Array.get(bean, i);
          if (b != null) {
            String name = null;
            if (objectName.charAt(objectName.length() - 1) == 's') {
              name = formatName(objectName.substring(0, objectName.length() - 1));
            }
            getBeanElements(element, name, b.getClass().getName(), b);
          } else {
            // Array element is null, so don't include it and decrement the # elements in the array
            int index = arrayType.indexOf("[");
            arrayType.replace(index + 1, index + 2, String.valueOf(--arrayLen));
          }
          if (includeTypeInfo) {
            element.setAttributeNS(
                NamespaceConstants.NSURI_SCHEMA_XSI,
                NamespaceConstants.NSPREFIX_SCHEMA_XSI + ":" + Constants.ATTR_TYPE,
                NamespaceConstants.NSPREFIX_SOAP_ENCODING + ":Array");
            element.setAttributeNS(
                NamespaceConstants.NSURI_SOAP_ENCODING,
                NamespaceConstants.NSPREFIX_SOAP_ENCODING + ":" + Constants.ATTR_ARRAY_TYPE,
                arrayInfo[0] + ":" + arrayType.toString());
          }
        }
      } else {
        int beanType = 0;
        String beanName = null;
        if (classOfBean != null) {
          if (classOfBean == Vector.class) {
            beanType = 1;
            beanName = "Vector";
          } else if (classOfBean == ArrayList.class) {
            beanType = 2;
            beanName = "ArrayList";
          } else if (classOfBean == LinkedList.class) {
            beanType = 3;
            beanName = "LinkedList";
          } else if (classOfBean == Hashtable.class) {
            beanType = 4;
            beanName = "Hashtable";
          } else if (classOfBean == Properties.class) {
            beanType = 5;
            beanName = "Properties";
          } else if ((classOfBean == HashMap.class) || (classOfBean == SortedMap.class)) {
            beanType = 6;
            beanName = "Map";
          }
        }
        if (beanType > 0) {
          String prefix = null;
          if ((beanType == 1) || (beanType == 5))
            prefix = NamespaceConstants.NSPREFIX_SOAP_ENCODING;
          if (beanType == 6) prefix = Constants.NS_PREFIX_XMLSOAP;
          else prefix = DEFAULT_NS_PREFIX;
          element = document.createElement(objectName);
          if (includeTypeInfo) {
            element.setAttributeNS(
                NamespaceConstants.NSURI_SCHEMA_XSI,
                NamespaceConstants.NSPREFIX_SCHEMA_XSI + ":" + Constants.ATTR_TYPE,
                prefix + ":" + beanName);
            if (bean == null)
              element.setAttributeNS(
                  NamespaceConstants.NSURI_SCHEMA_XSI,
                  NamespaceConstants.NSPREFIX_SCHEMA_XSI + ":null",
                  "true");
          }
          parentElement.appendChild(element);
          if ((beanType >= 1) && (beanType <= 3)) {
            AbstractCollection collection = (AbstractCollection) bean;
            // Get the bean objects from the vector and serialize each
            Iterator it = collection.iterator();
            while (it.hasNext()) {
              Object b = it.next();
              String name = null;
              if (b != null) {
                if (objectName.charAt(objectName.length() - 1) == 's') {
                  name = formatName(objectName.substring(0, objectName.length() - 1));
                } else name = "item";
              }
              getBeanElements(element, name, b.getClass().getName(), b);
            }
          } else if ((beanType == 4) || (beanType == 5)) {
            Hashtable hashtable = (Hashtable) bean;
            // Get the bean objects from the hashtable or properties and serialize each
            Enumeration en = hashtable.keys();
            while (en.hasMoreElements()) {
              Object key = en.nextElement();
              String keyClassName = key.getClass().getName();
              Object value = hashtable.get(key);
              String beanClassName = null;
              if (value != null) beanClassName = value.getClass().getName();
              Element itemElement = document.createElement("item");
              element.appendChild(itemElement);
              getBeanElements(itemElement, "key", keyClassName, key);
              getBeanElements(itemElement, "value", beanClassName, value);
            }
          } else if (beanType == 6) {
            Map map = null;
            if (classOfBean == HashMap.class) map = (HashMap) bean;
            else if (classOfBean == SortedMap.class) map = (SortedMap) bean;
            // Get the bean objects from the hashmap and serialize each
            Set set = map.keySet();
            Iterator it = set.iterator();
            while (it.hasNext()) {
              Object key = it.next();
              String keyClassName = key.getClass().getName();
              Object value = map.get(key);
              String beanClassName = null;
              if (value != null) beanClassName = value.getClass().getName();
              Element itemElement = document.createElement("item");
              element.appendChild(itemElement);
              getBeanElements(itemElement, "key", keyClassName, key);
              getBeanElements(itemElement, "value", beanClassName, value);
            }
          }
        } else {
          // Create a parent element for this bean's properties
          if (objectName.charAt(objectName.length() - 1) == ';')
            objectName =
                new StringBuffer(objectName).deleteCharAt(objectName.length() - 1).toString();
          objectName = formatName(objectName);
          element = document.createElement(objectName);
          parentElement.appendChild(element);
          if (includeTypeInfo) {
            StringBuffer className = new StringBuffer(objectType);
            element.setAttributeNS(
                NamespaceConstants.NSURI_SCHEMA_XSI,
                NamespaceConstants.NSPREFIX_SCHEMA_XSI + ":" + Constants.ATTR_TYPE,
                nsPrefix + ":" + className.delete(0, className.lastIndexOf(".") + 1).toString());
          }
          if (classOfBean != null) {
            // Get an array of property descriptors
            BeanInfo bi = Introspector.getBeanInfo(classOfBean);
            PropertyDescriptor[] pds = bi.getPropertyDescriptors();
            // For each property of the bean, get a SOAPBodyElement that
            // represents the individual property. Append that SOAPBodyElement
            // to the class name element of the SOAP body.
            for (int i = 0; i < pds.length; i++) {
              PropertyDescriptor pd = pds[i];
              getBeanElementProperties(element, bean, pd);
            }
          } else {
            if (includeTypeInfo)
              element.setAttributeNS(
                  NamespaceConstants.NSURI_SCHEMA_XSI,
                  NamespaceConstants.NSPREFIX_SCHEMA_XSI + ":null",
                  "true");
          }
        }
      }
    }
  }
Пример #5
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());
    }
  }
  public String getPublicPropertiesForClasses(String classNames[]) {
    StringBuilder result = new StringBuilder();
    String className = null;
    ArrayList publicFields = new ArrayList();
    result.append("<classDefinitions>");
    if (classNames != null && classNames.length > 0) {
      for (int i = 0; i < classNames.length; i++) {
        className = classNames[i];
        if (className != null) {
          result.append("<classDefinition>");
          try {
            Class c = Class.forName(className);
            Field fields[] = c.getFields();
            Field field = null;
            if (fields != null) {
              for (int k = 0; k < fields.length; k++) {
                field = fields[k];
                if (field != null)
                  publicFields.add(
                      (new StringBuilder(String.valueOf(field.getName())))
                          .append(",")
                          .append(field.getType().getName())
                          .toString());
              }
            }
            try {
              BeanInfo b = Introspector.getBeanInfo(c);
              result.append(
                  (new StringBuilder("<classSimpleName>"))
                      .append(c.getSimpleName())
                      .append("</classSimpleName>")
                      .toString());
              result.append(
                  (new StringBuilder("<classFullName>"))
                      .append(c.getName())
                      .append("</classFullName>")
                      .toString());
              Package pack = c.getPackage();
              String packStr = "";
              if (pack != null) packStr = pack.getName();
              result.append(
                  (new StringBuilder("<packageName>"))
                      .append(packStr)
                      .append("</packageName>")
                      .toString());
              PropertyDescriptor pds[] = b.getPropertyDescriptors();
              if (pds != null) {
                for (int propCount = 0; propCount < pds.length; propCount++) {
                  PropertyDescriptor pd = pds[propCount];
                  String propertyName = pd.getName();
                  Method readMethod = pd.getReadMethod();
                  Method writeMethod = pd.getWriteMethod();
                  if (readMethod != null
                      && isPublicAccessor(readMethod.getModifiers())
                      && writeMethod != null
                      && isPublicAccessor(writeMethod.getModifiers()))
                    publicFields.add(
                        (new StringBuilder(String.valueOf(propertyName)))
                            .append(",")
                            .append(pd.getPropertyType().getName())
                            .toString());
                }
              }
            } catch (Exception e) {
              e.printStackTrace();
            }
            if (publicFields != null && publicFields.size() > 0) {
              String temp = null;
              result.append("<publicFields>");
              for (int counter = 0; counter < publicFields.size(); counter++) {
                temp = (String) publicFields.get(counter);
                if (temp != null) {
                  String pubTemp[] = temp.split(",");
                  if (pubTemp.length == 2) {
                    result.append("<publicField>");
                    result.append(
                        (new StringBuilder("<publicFieldName>"))
                            .append(pubTemp[0])
                            .append("</publicFieldName>")
                            .toString());
                    result.append(
                        (new StringBuilder("<publicFieldType>"))
                            .append(pubTemp[1])
                            .append("</publicFieldType>")
                            .toString());
                    result.append("</publicField>");
                  }
                }
              }

              result.append("</publicFields>");
            }
          } catch (ClassNotFoundException e) {
            result.append(
                (new StringBuilder("<classFullName>"))
                    .append(className)
                    .append("</classFullName>")
                    .toString());
            result.append(
                (new StringBuilder("<error>Problem retrieving "))
                    .append(className)
                    .append(" information</error>")
                    .toString());
            System.out.println(e.getMessage());
          }
          result.append("</classDefinition>");
        }
      }
    }
    result.append("</classDefinitions>");
    return result.toString();
  }
Пример #7
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();
    }
  }