public void renderValue(
      Object aObj, JSONObject aObjectElement, JSONMarshall aMarshall, HashMap aPool)
      throws MarshallException {
    final JSONObject lElements = new JSONObject();
    aObjectElement.getValue().put(JSONMarshall.RNDR_ATTR_VALUE, lElements);

    try {
      Class lClass = aObj.getClass();
      PropertyDescriptor[] lPropDesc =
          Introspector.getBeanInfo(lClass, Introspector.USE_ALL_BEANINFO).getPropertyDescriptors();
      for (int i = 0; i < lPropDesc.length; i++) {
        Method lReader = lPropDesc[i].getReadMethod();
        Method lWriter = lPropDesc[i].getWriteMethod();
        String lPropName = lPropDesc[i].getName();

        // Only serialize if the property is READ-WRITE.
        if (lReader != null && lWriter != null) {
          lElements
              .getValue()
              .put(lPropName, aMarshall.marshallImpl(lReader.invoke(aObj, new Object[] {}), aPool));
        }
      }
    } catch (IntrospectionException e) {
      final String lMsg = "Error while introspecting JavaBean.";
      throw new MarshallException(lMsg);
    } catch (IllegalAccessException e) {
      final String lMsg = "Illegal access while trying to fetch a bean property (1).";
      throw new MarshallException(lMsg);
    } catch (InvocationTargetException e) {
      final String lMsg = "Illegal access while trying to fetch a bean property (2).";
      throw new MarshallException(lMsg);
    }
  }
Beispiel #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;
   }
 }
  public BeanInfo[] getAdditionalBeanInfo() {
    try {
      BeanInfo hPubBi1 = Introspector.getBeanInfo(RestitutionCompGetData.class.getSuperclass());

      BeanInfo[] arrayOfBIs = {hPubBi1};
      return arrayOfBIs;
    } catch (IntrospectionException e) {
      e.printStackTrace();
    }

    return null;
  }
  public BeanInfo[] getAdditionalBeanInfo() {
    try {
      BeanInfo hPubBi1 = Introspector.getBeanInfo(LastActionHistoryResults.class.getSuperclass());

      BeanInfo[] arrayOfBIs = {hPubBi1};
      return arrayOfBIs;
    } catch (IntrospectionException e) {
      e.printStackTrace();
    }

    return null;
  }
Beispiel #5
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());
    }
  }
Beispiel #6
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");
          }
        }
      }
    }
  }
  public Object parseValue(JSONObject aObjectElement, JSONMarshall aMarshall, HashMap aPool)
      throws MarshallException {
    JSONMarshall.requireStringAttribute(aObjectElement, JSONMarshall.RNDR_ATTR_CLASS);
    String lBeanClassName =
        ((JSONString) aObjectElement.get(JSONMarshall.RNDR_ATTR_CLASS)).getValue();

    String lId = null;
    try {
      JSONMarshall.requireStringAttribute(aObjectElement, JSONMarshall.RNDR_ATTR_ID);
      lId = ((JSONString) aObjectElement.get(JSONMarshall.RNDR_ATTR_ID)).getValue();
    } catch (Exception eIgnore) {
    }

    try {
      Class lBeanClass = Class.forName(lBeanClassName);
      Object lBean = null;

      lBean = lBeanClass.newInstance();
      if (lId != null) aPool.put(lId, lBean);

      JSONObject lProperties = (JSONObject) aObjectElement.get(JSONMarshall.RNDR_ATTR_VALUE);
      Iterator<String> lElIter = lProperties.getValue().keySet().iterator();

      while (lElIter.hasNext()) {
        // Fetch subelement information.
        String lPropname = lElIter.next();
        JSONObject lSubEl = (JSONObject) lProperties.get(lPropname);
        Object lProp = aMarshall.unmarshallImpl(lSubEl, aPool);

        // Put the property in the bean.
        boolean lFoundWriter = false;
        PropertyDescriptor[] lPropDesc =
            Introspector.getBeanInfo(lBeanClass, Introspector.USE_ALL_BEANINFO)
                .getPropertyDescriptors();
        for (int i = 0; i < lPropDesc.length; i++) {
          if (lPropDesc[i].getName().equals(lPropname)) {
            lFoundWriter = true;
            Method lWriter = lPropDesc[i].getWriteMethod();
            if (lWriter == null) {
              final String lMsg =
                  "Could not find a setter for prop: " + lPropname + " in class: " + lBeanClassName;
              throw new MarshallException(lMsg);
            }
            lWriter.invoke(lBean, new Object[] {lProp});
            break;
          }
        }

        if (!lFoundWriter) {
          final String lMsg =
              "Could not find a setter for prop: " + lPropname + " in class: " + lBeanClassName;
          throw new MarshallException(lMsg);
        }
      }

      return lBean;
    } catch (ClassNotFoundException e) {
      final String lMsg = "Could not find JavaBean class: " + lBeanClassName;
      throw new MarshallException(lMsg);
    } catch (IllegalAccessException e) {
      final String lMsg =
          "IllegalAccessException while trying to instantiate bean: " + lBeanClassName;
      throw new MarshallException(lMsg);
    } catch (InstantiationException e) {
      final String lMsg =
          "InstantiationException while trying to instantiate bean: " + lBeanClassName;
      throw new MarshallException(lMsg);
    } catch (IntrospectionException e) {
      final String lMsg = "IntrospectionException while trying to fill bean: " + lBeanClassName;
      throw new MarshallException(lMsg);
    } catch (InvocationTargetException e) {
      final String lMsg = "InvocationTargetException while trying to fill bean: " + lBeanClassName;
      throw new MarshallException(lMsg);
    }
  }
  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();
  }
  private JSONArray getClassProperties(Class<?> clazz, int level) throws IntrospectionException {
    JSONArray arr = new JSONArray();
    TypeDiscoverer td = new TypeDiscoverer();
    try {
      for (PropertyDescriptor pd : Introspector.getBeanInfo(clazz).getPropertyDescriptors()) {
        Method readMethod = pd.getReadMethod();
        if (readMethod != null) {
          if (readMethod.getDeclaringClass() == java.lang.Enum.class) {
            // skip getDeclaringClass
            continue;
          } else if ("class".equals(pd.getName())) {
            // skip getClass
            continue;
          }
        } else {
          // yields com.datatorrent.api.Context on JDK6 and
          // com.datatorrent.api.Context.OperatorContext with JDK7
          if ("up".equals(pd.getName())
              && com.datatorrent.api.Context.class.isAssignableFrom(pd.getPropertyType())) {
            continue;
          }
        }
        // LOG.info("name: " + pd.getName() + " type: " + pd.getPropertyType());

        Class<?> propertyType = pd.getPropertyType();
        if (propertyType != null) {
          JSONObject propertyObj = new JSONObject();
          propertyObj.put("name", pd.getName());
          propertyObj.put("canGet", readMethod != null);
          propertyObj.put("canSet", pd.getWriteMethod() != null);
          if (readMethod != null) {
            for (Class<?> c = clazz; c != null; c = c.getSuperclass()) {
              OperatorClassInfo oci = classInfo.get(c.getName());
              if (oci != null) {
                MethodInfo getMethodInfo = oci.getMethods.get(readMethod.getName());
                if (getMethodInfo != null) {
                  addTagsToProperties(getMethodInfo, propertyObj);
                  break;
                }
              }
            }
            // type can be a type symbol or parameterized type
            td.setTypeArguments(clazz, readMethod.getGenericReturnType(), propertyObj);
          } else {
            if (pd.getWriteMethod() != null) {
              td.setTypeArguments(
                  clazz, pd.getWriteMethod().getGenericParameterTypes()[0], propertyObj);
            }
          }
          // if (!propertyType.isPrimitive() && !propertyType.isEnum() && !propertyType.isArray() &&
          // !propertyType.getName().startsWith("java.lang") && level < MAX_PROPERTY_LEVELS) {
          //  propertyObj.put("properties", getClassProperties(propertyType, level + 1));
          // }
          arr.put(propertyObj);
        }
      }
    } catch (JSONException ex) {
      throw new RuntimeException(ex);
    }
    return arr;
  }
Beispiel #10
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();
    }
  }