Document parseDocument(String filename) throws Exception {
   FileReader reader = new FileReader(filename);
   String firstLine = new BufferedReader(reader).readLine();
   reader.close();
   Document document = null;
   if (firstLine.startsWith("<?xml")) {
     System.err.println("XML detected; using default XML parser.");
   } else {
     try {
       Class nekoParserClass = Class.forName("org.cyberneko.html.parsers.DOMParser");
       Object parser = nekoParserClass.newInstance();
       Method parse = nekoParserClass.getMethod("parse", new Class[] {String.class});
       Method getDocument = nekoParserClass.getMethod("getDocument", new Class[0]);
       parse.invoke(parser, filename);
       document = (Document) getDocument.invoke(parser);
     } catch (Exception e) {
       System.err.println("NekoHTML HTML parser not found; HTML4 support disabled.");
     }
   }
   if (document == null) {
     DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
     try { // http://www.w3.org/blog/systeam/2008/02/08/w3c_s_excessive_dtd_traffic
       factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
     } catch (ParserConfigurationException e) {
       System.err.println("Warning: Could not disable external DTD loading");
     }
     DocumentBuilder builder = factory.newDocumentBuilder();
     document = builder.parse(filename);
   }
   return document;
 }
Пример #2
0
  static <T> T set(Class<T> interf, Object value) {
    Properties p = new Properties();
    Method ms[] = interf.getMethods();

    for (Method m : ms) {
      p.put(m.getName(), value);
    }
    return Configurable.createConfigurable(interf, (Map<Object, Object>) p);
  }
 Object invoke(String method, Class[] argtypes, Object[] args) throws InvocationTargetException {
   try {
     Method m = fact.getClass().getMethod(method, argtypes);
     return m.invoke(fact, args);
   } catch (NoSuchMethodException e) {
     throw new RuntimeException(e);
   } catch (IllegalAccessException e) {
     throw new RuntimeException(e);
   }
 }
  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;
  }
Пример #5
0
  /**
   * Reads XML element(s) into an indexed bean property by first locating the XML element(s)
   * corresponding to this property.
   *
   * @param ob The bean whose property is being set
   * @param desc The property that will be set
   * @param nodes The list of XML items that may contain the property
   * @throws IOException If there is an error reading the document
   */
  public void readIndexedProperty(
      Object ob, IndexedPropertyDescriptor desc, NodeList nodes, NamedNodeMap attrs)
      throws IOException {
    // Create a vector to hold the property values
    Vector v = new Vector();

    int numAttrs = attrs.getLength();

    for (int i = 0; i < numAttrs; i++) {
      // See if this attribute matches the property name
      if (namesMatch(desc.getName(), attrs.item(i).getNodeName())) {
        // Get the property value
        Object obValue = getObjectValue(desc, attrs.item(i).getNodeValue());

        if (obValue != null) {
          // Add the value to the list of values to be set
          v.addElement(obValue);
        }
      }
    }

    int numNodes = nodes.getLength();

    for (int i = 0; i < numNodes; i++) {
      Node node = nodes.item(i);

      // Skip non-element nodes
      if (!(node instanceof Element)) continue;

      Element element = (Element) node;

      // See if this element tag matches the property name
      if (namesMatch(desc.getName(), element.getTagName())) {
        // Get the property value
        Object obValue = getObjectValue(desc, element);

        if (obValue != null) {
          // Add the value to the list of values to be set
          v.addElement(obValue);
        }
      }
    }

    // Get the method used to set the property value
    Method setter = desc.getWriteMethod();

    // If this property has no setter, don't write it
    if (setter == null) return;

    // Create a new array of property values
    Object propArray = Array.newInstance(desc.getPropertyType().getComponentType(), v.size());

    // Copy the vector into the array
    v.copyInto((Object[]) propArray);

    try {
      // Store the array of property values
      setter.invoke(ob, new Object[] {propArray});
    } catch (InvocationTargetException exc) {
      throw new IOException("Error setting property " + desc.getName() + ": " + exc.toString());
    } catch (IllegalAccessException exc) {
      throw new IOException("Error setting property " + desc.getName() + ": " + exc.toString());
    }
  }
Пример #6
0
  /**
   * Reads an XML element into a bean property by first locating the XML element corresponding to
   * this property.
   *
   * @param ob The bean whose property is being set
   * @param desc The property that will be set
   * @param nodes The list of XML items that may contain the property
   * @throws IOException If there is an error reading the document
   */
  public void readProperty(Object ob, PropertyDescriptor desc, NodeList nodes, NamedNodeMap attrs)
      throws IOException {
    int numAttrs = attrs.getLength();

    for (int i = 0; i < numAttrs; i++) {
      // See if the attribute name matches the property name
      if (namesMatch(desc.getName(), attrs.item(i).getNodeName())) {
        // Get the method used to set this property
        Method setter = desc.getWriteMethod();

        // If this object has no setter, don't bother writing it
        if (setter == null) continue;

        // Get the value of the property
        Object obValue = getObjectValue(desc, attrs.item(i).getNodeValue());
        if (obValue != null) {
          try {
            // Set the property value
            setter.invoke(ob, new Object[] {obValue});
          } catch (InvocationTargetException exc) {
            throw new IOException(
                "Error setting property " + desc.getName() + ": " + exc.toString());
          } catch (IllegalAccessException exc) {
            throw new IOException(
                "Error setting property " + desc.getName() + ": " + exc.toString());
          }
        }

        return;
      }
    }

    int numNodes = nodes.getLength();

    Vector arrayBuild = null;

    for (int i = 0; i < numNodes; i++) {
      Node node = nodes.item(i);

      // If this node isn't an element, skip it
      if (!(node instanceof Element)) continue;

      Element element = (Element) node;

      // See if the tag name matches the property name
      if (namesMatch(desc.getName(), element.getTagName())) {
        // Get the method used to set this property
        Method setter = desc.getWriteMethod();

        // If this object has no setter, don't bother writing it
        if (setter == null) continue;

        // Get the value of the property
        Object obValue = getObjectValue(desc, element);

        // 070201 MAW: Modified from change submitted by Steve Poulson
        if (setter.getParameterTypes()[0].isArray()) {
          if (arrayBuild == null) {
            arrayBuild = new Vector();
          }
          arrayBuild.addElement(obValue);

          // 070201 MAW: Go ahead and read through the rest of the nodes in case
          //             another one matches the array. This has the effect of skipping
          //             over the "return" statement down below
          continue;
        }

        if (obValue != null) {
          try {
            // Set the property value
            setter.invoke(ob, new Object[] {obValue});
          } catch (InvocationTargetException exc) {
            throw new IOException(
                "Error setting property " + desc.getName() + ": " + exc.toString());
          } catch (IllegalAccessException exc) {
            throw new IOException(
                "Error setting property " + desc.getName() + ": " + exc.toString());
          }
        }
        return;
      }
    }

    // If we build a vector of array members, convert the vector into
    // an array and save it in the property
    if (arrayBuild != null) {
      // Get the method used to set this property
      Method setter = desc.getWriteMethod();

      if (setter == null) return;

      Object[] obValues = (Object[]) Array.newInstance(desc.getPropertyType(), arrayBuild.size());

      arrayBuild.copyInto(obValues);

      try {
        setter.invoke(ob, new Object[] {obValues});
      } catch (InvocationTargetException exc) {
        throw new IOException("Error setting property " + desc.getName() + ": " + exc.toString());
      } catch (IllegalAccessException exc) {
        throw new IOException("Error setting property " + desc.getName() + ": " + exc.toString());
      }

      return;
    }
  }