Exemplo n.º 1
0
  /**
   * Examines a property's type to see which method should be used to parse the property's value.
   *
   * @param desc The description of the property
   * @param value The value of the XML attribute containing the prop value
   * @return The value stored in the element
   * @throws IOException If there is an error reading the document
   */
  public Object getObjectValue(PropertyDescriptor desc, String value) throws IOException {
    // Find out what kind of property it is
    Class type = desc.getPropertyType();

    // If it's an array, get the base type
    if (type.isArray()) {
      type = type.getComponentType();
    }

    // For native types, object wrappers for natives, and strings, use the
    // basic parse routine
    if (type.equals(Integer.TYPE)
        || type.equals(Long.TYPE)
        || type.equals(Short.TYPE)
        || type.equals(Byte.TYPE)
        || type.equals(Boolean.TYPE)
        || type.equals(Float.TYPE)
        || type.equals(Double.TYPE)
        || Integer.class.isAssignableFrom(type)
        || Long.class.isAssignableFrom(type)
        || Short.class.isAssignableFrom(type)
        || Byte.class.isAssignableFrom(type)
        || Boolean.class.isAssignableFrom(type)
        || Float.class.isAssignableFrom(type)
        || Double.class.isAssignableFrom(type)) {
      return parseBasicType(type, value);
    } else if (String.class.isAssignableFrom(type)) {
      return value;
    } else if (java.util.Date.class.isAssignableFrom(type)) {
      // If it's a date, use the date parser
      return parseDate(value, JOXDateHandler.determineDateFormat());
    } else {
      return null;
    }
  }
Exemplo n.º 2
0
  private static SAXParserFactory createFastSAXParserFactory()
      throws ParserConfigurationException, SAXException {
    if (fastParserFactoryClass == null) {
      try {
        fastParserFactoryClass =
            Class.forName("org.apache.crimson.jaxp.SAXParserFactoryImpl"); // NOI18N
      } catch (Exception ex) {
        useFastSAXParserFactory = false;
        if (System.getProperty("java.version").startsWith("1.4")) { // NOI18N
          ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, ex);
        }
      }
    }
    if (fastParserFactoryClass != null) {
      try {
        SAXParserFactory factory = (SAXParserFactory) fastParserFactoryClass.newInstance();

        return factory;
      } catch (Exception ex) {
        useFastSAXParserFactory = false;
        throw new ParserConfigurationException(ex.getMessage());
      }
    }

    return SAXParserFactory.newInstance();
  }
Exemplo n.º 3
0
 private void guessClassReference(TypedValues list, String name) {
   try {
     Class<?> type = Class.forName(fixPotentialArrayName(name));
     list.add(new TypedValue(type.getClass(), type));
   } catch (ClassNotFoundException y) {
     _logger.fine(name + " looked like a class reference but is not");
   }
 }
Exemplo n.º 4
0
  static {
    if (!Boolean.getBoolean(GridSystemProperties.GG_JETTY_LOG_NO_OVERRIDE)) {
      String ctgrJetty = "org.eclipse.jetty"; // WARN for this category.
      String ctgrJettyUtil = "org.eclipse.jetty.util.log"; // ERROR for this...
      String ctgrJettyUtilComp = "org.eclipse.jetty.util.component"; // ...and this.

      try {
        Class<?> logCls = Class.forName("org.apache.log4j.Logger");

        Object logJetty = logCls.getMethod("getLogger", String.class).invoke(logCls, ctgrJetty);
        Object logJettyUtil =
            logCls.getMethod("getLogger", String.class).invoke(logCls, ctgrJettyUtil);
        Object logJettyUtilComp =
            logCls.getMethod("getLogger", String.class).invoke(logCls, ctgrJettyUtilComp);

        Class<?> lvlCls = Class.forName("org.apache.log4j.Level");

        Object warnLvl = lvlCls.getField("WARN").get(null);
        Object errLvl = lvlCls.getField("ERROR").get(null);

        logJetty.getClass().getMethod("setLevel", lvlCls).invoke(logJetty, warnLvl);
        logJettyUtil.getClass().getMethod("setLevel", lvlCls).invoke(logJetty, errLvl);
        logJettyUtilComp.getClass().getMethod("setLevel", lvlCls).invoke(logJetty, errLvl);
      } catch (Exception ignored) {
        // No-op.
      }
    }
  }
Exemplo n.º 5
0
  private void injectProperty(
      Object bean, Class<?> type, Object property, String alias, TypedValueGroup arguments)
      throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
    NoSuchMethodException nsme = null;

    if (arguments != null && arguments.size() > 0) {
      Object[] props = new Object[arguments.size() + 1];
      props[0] = property;
      Class<?>[] types = new Class<?>[arguments.size() + 1];
      types[0] = type;

      arguments.reset();
      while (arguments.load(props, 1)) {
        try {
          addSetProperty(bean, types, alias, props);
          return;
        } catch (NoSuchMethodException x) {
          // not a problem
          nsme = x;
        }
      }
    } else {
      try {
        addSetProperty(bean, new Class<?>[] {type}, alias, property);
        return;
      } catch (NoSuchMethodException x) {
        // not a problem
        nsme = x;
      }
    }

    // now try the super classes
    Class<?>[] interfaces = type.getInterfaces();
    for (Class<?> face : interfaces) {
      try {
        injectProperty(bean, face, property, alias, arguments);
        return;
      } catch (NoSuchMethodException x) {
        continue;
      }
    }
    Class<?> supertype = type.getSuperclass();
    if (supertype != null) {
      injectProperty(bean, supertype, property, alias, arguments);
    } else {
      throw nsme;
    }
  }
Exemplo n.º 6
0
 /**
  * This creates an empty <code>Document</code> object based on a specific parser implementation.
  *
  * @return <code>Document</code> - created DOM Document.
  * @throws JDOMException when errors occur.
  */
 public Document createDocument() throws JDOMException {
   try {
     return (Document) Class.forName("org.apache.xerces.dom.DocumentImpl").newInstance();
   } catch (Exception e) {
     throw new JDOMException(
         e.getClass().getName() + ": " + e.getMessage() + " when creating document", e);
   }
 }
Exemplo n.º 7
0
 public String toString() {
   return "type="
       + type.getSimpleName()
       + ",data="
       + data.getClass().getSimpleName()
       + ':'
       + data;
 }
Exemplo n.º 8
0
 private static InputSource getConfigSource(Class pAppClass) throws DataNotFoundException {
   URL resource = pAppClass.getResource(CONFIG_FILE_NAME);
   String resourceFileName = resource.toExternalForm();
   File resourceFile = new File(resourceFileName);
   InputStream configResourceStream = pAppClass.getResourceAsStream(CONFIG_FILE_NAME);
   if (null == configResourceStream) {
     throw new DataNotFoundException(
         "unable to find XML configuration file resource: "
             + CONFIG_FILE_NAME
             + " for class: "
             + pAppClass.getName());
   }
   InputSource inputSource = new InputSource(configResourceStream);
   if (!resourceFile.exists()) {
     inputSource.setSystemId(resourceFileName);
   }
   return (inputSource);
 }
Exemplo n.º 9
0
  static {
    try {
      // Create factory
      documentBuilderFactory =
          (DocumentBuilderFactory)
              Class.forName("orbeon.apache.xerces.jaxp.DocumentBuilderFactoryImpl").newInstance();

      // Configure factory
      documentBuilderFactory.setNamespaceAware(true);
    } catch (Exception e) {
      throw new OXFException(e);
    }
  }
Exemplo n.º 10
0
 public HTMLParser() {
   _errorReport = new ErrorReportImpl(ErrorReport.STOP_AT_NO_ERROR, ErrorReport.REPORT_ALL_ERRORS);
   _parser = new HTMLSAXParser(_errorReport);
   try {
     Class.forName("org.apache.xerces.dom.ElementImpl");
     //	    _builder = new HTMLBuilder();
     // Tweaked to avoid trying to use the Xerces HTML DOM (org.apache.html.dom)
     // (BBP)
   } catch (ClassNotFoundException except) {
     _builder = new SAXBuilder();
   }
   _parser.setDocumentHandler(_builder);
 }
Exemplo n.º 11
0
  /**
   * This creates a new <code>{@link Document}</code> from an existing <code>InputStream</code> by
   * letting a DOM parser handle parsing using the supplied stream.
   *
   * @param in <code>InputStream</code> to parse.
   * @param validate <code>boolean</code> to indicate if validation should occur.
   * @return <code>Document</code> - instance ready for use.
   * @throws IOException when I/O error occurs.
   * @throws JDOMException when errors occur in parsing.
   */
  public Document getDocument(InputStream in, boolean validate) throws IOException, JDOMException {

    try {
      // Load the parser class
      Class parserClass = Class.forName("org.apache.xerces.parsers.DOMParser");
      Object parser = parserClass.newInstance();

      // Set validation
      Method setFeature =
          parserClass.getMethod("setFeature", new Class[] {java.lang.String.class, boolean.class});
      setFeature.invoke(
          parser, new Object[] {"http://xml.org/sax/features/validation", new Boolean(validate)});

      // Set namespaces true
      setFeature.invoke(
          parser, new Object[] {"http://xml.org/sax/features/namespaces", new Boolean(true)});

      // Set the error handler
      if (validate) {
        Method setErrorHandler =
            parserClass.getMethod("setErrorHandler", new Class[] {ErrorHandler.class});
        setErrorHandler.invoke(parser, new Object[] {new BuilderErrorHandler()});
      }

      // Parse the document
      Method parse = parserClass.getMethod("parse", new Class[] {org.xml.sax.InputSource.class});
      parse.invoke(parser, new Object[] {new InputSource(in)});

      // Get the Document object
      Method getDocument = parserClass.getMethod("getDocument", null);
      Document doc = (Document) getDocument.invoke(parser, null);

      return doc;
    } catch (InvocationTargetException e) {
      Throwable targetException = e.getTargetException();
      if (targetException instanceof org.xml.sax.SAXParseException) {
        SAXParseException parseException = (SAXParseException) targetException;
        throw new JDOMException(
            "Error on line "
                + parseException.getLineNumber()
                + " of XML document: "
                + parseException.getMessage(),
            e);
      } else if (targetException instanceof IOException) {
        IOException ioException = (IOException) targetException;
        throw ioException;
      } else {
        throw new JDOMException(targetException.getMessage(), e);
      }
    } catch (Exception e) {
      throw new JDOMException(e.getClass().getName() + ": " + e.getMessage(), e);
    }
  }
Exemplo n.º 12
0
  /**
   * Reads an string into a basic type
   *
   * @param type The type of the string to read
   * @param str The string containing the value
   * @return The parsed value of the string
   */
  public static Object parseBasicType(Class type, String str) {
    // Parse the text based on the property type

    if (type.equals(Integer.TYPE) || Integer.class.isAssignableFrom(type)) {
      return new Integer(str);
    } else if (type.equals(Long.TYPE) || Long.class.isAssignableFrom(type)) {
      return new Long(str);
    } else if (type.equals(Short.TYPE) || Short.class.isAssignableFrom(type)) {
      return new Short(str);
    } else if (type.equals(Byte.TYPE) || Byte.class.isAssignableFrom(type)) {
      return new Byte(str);
    } else if (type.equals(Boolean.TYPE) || Boolean.class.isAssignableFrom(type)) {
      return new Boolean(str);
    } else if (type.equals(Float.TYPE) || Float.class.isAssignableFrom(type)) {
      return new Float(str);
    } else if (type.equals(Double.TYPE) || Double.class.isAssignableFrom(type)) {
      return new Double(str);
    }

    return null;
  }
Exemplo n.º 13
0
  /**
   * Creates a SAX XMLReader.
   *
   * @return <code>XMLReader</code> a SAX2 parser.
   * @throws Exception if no parser can be created.
   */
  protected XMLReader createParser() throws Exception {
    XMLReader parser = null;

    // Try using JAXP...
    // Note we need JAXP 1.1, and if JAXP 1.0 is all that's
    // available then the getXMLReader call fails and we skip
    // to the hard coded default parser
    try {
      Class factoryClass = Class.forName("javax.xml.parsers.SAXParserFactory");

      // MODIFIED: Added (Class[]) and (Object[]) cast sentences in "null" parameters
      // to avoid warnings during compilation

      // factory = SAXParserFactory.newInstance();
      Method newParserInstance = factoryClass.getMethod("newInstance", (Class[]) null);
      Object factory = newParserInstance.invoke(null, (Object[]) null);

      // jaxpParser = factory.newSAXParser();
      Method newSAXParser = factoryClass.getMethod("newSAXParser", (Class[]) null);
      Object jaxpParser = newSAXParser.invoke(factory, (Object[]) null);

      // parser = jaxpParser.getXMLReader();
      Class parserClass = jaxpParser.getClass();
      Method getXMLReader = parserClass.getMethod("getXMLReader", (Class[]) null);
      parser = (XMLReader) getXMLReader.invoke(jaxpParser, (Object[]) null);
    } catch (ClassNotFoundException e) {
      // e.printStackTrace();
    } catch (InvocationTargetException e) {
      // e.printStackTrace();
    } catch (NoSuchMethodException e) {
      // e.printStackTrace();
    } catch (IllegalAccessException e) {
      // e.printStackTrace();
    }

    // Check to see if we got a parser yet, if not, try to use a
    // hard coded default
    if (parser == null) {
      parser = XMLReaderFactory.createXMLReader("org.apache.xerces.parsers.SAXParser");
    }
    return parser;
  }
Exemplo n.º 14
0
  /**
   * Examines a property's type to see which method should be used to parse the property's value.
   *
   * @param desc The description of the property
   * @param element The XML element containing the property value
   * @return The value stored in the element
   * @throws IOException If there is an error reading the document
   */
  public Object getObjectValue(PropertyDescriptor desc, Element element) throws IOException {
    // Find out what kind of property it is
    Class type = desc.getPropertyType();

    // If it's an array, get the base type
    if (type.isArray()) {
      type = type.getComponentType();
    }

    // For native types, object wrappers for natives, and strings, use the
    // basic parse routine
    if (type.equals(Integer.TYPE)
        || type.equals(Long.TYPE)
        || type.equals(Short.TYPE)
        || type.equals(Byte.TYPE)
        || type.equals(Boolean.TYPE)
        || type.equals(Float.TYPE)
        || type.equals(Double.TYPE)
        || Integer.class.isAssignableFrom(type)
        || Long.class.isAssignableFrom(type)
        || Short.class.isAssignableFrom(type)
        || Byte.class.isAssignableFrom(type)
        || Boolean.class.isAssignableFrom(type)
        || Float.class.isAssignableFrom(type)
        || Double.class.isAssignableFrom(type)
        || String.class.isAssignableFrom(type)) {
      return readBasicType(type, element);
    } else if (java.util.Date.class.isAssignableFrom(type)) {
      // If it's a date, use the date parser
      return readDate(element);
    } else {
      try {
        // If it's an object, create a new instance of the object (it should
        // be a bean, or there will be trouble)
        Object newOb = type.newInstance();

        // Copy the XML element into the bean
        readObject(newOb, element);

        return newOb;
      } catch (InstantiationException exc) {
        throw new IOException(
            "Error creating object for " + desc.getName() + ": " + exc.toString());
      } catch (IllegalAccessException exc) {
        throw new IOException(
            "Error creating object for " + desc.getName() + ": " + exc.toString());
      }
    }
  }
Exemplo n.º 15
0
    /**
     * main class used for command line invocation
     * @param args the String[] consisting of the command line arguments
    **/
    public static void main(String[] args) {


        CommandLineOptions allOptions = new CommandLineOptions();

        //-- filename flag
        allOptions.addFlag("i", "filename", "Sets the input filename");

        //-- package name flag
        allOptions.addFlag("package", "package-name", "Sets the package name", true);

        //-- destination directory
        String desc = "Sets the destination output directory";
        allOptions.addFlag("dest", "dest-dir", desc, true);

        //-- line break flag
        desc = "Sets the line separator style for the desired platform";
        allOptions.addFlag("line-separator", "( unix | mac | win)", desc, true);

        //-- Force flag
        desc = "Suppresses non fatal warnings, such as overwriting files.";
        allOptions.addFlag("f", "", desc, true);

        //-- Help flag
        desc = "Displays this help screen.";
        allOptions.addFlag("h", "", desc, true);

        //-- verbose flag
        desc = "Prints out additional messages when creaing source";
        allOptions.addFlag("verbose", "", desc, true);

        //-- no descriptors flag
        desc = "Disables the generation of the Class descriptors";
        allOptions.addFlag("nodesc", "", desc, true);

        //-- source generator types name flag
        desc = "Sets the source generator types name (SGTypeFactory)";
        allOptions.addFlag("types", "types", desc, true);

        //-- XXX maintained temporarily
        allOptions.addFlag("type-factory", "classname", "", true);

        //-- no marshalling framework methods
		desc = "Disables the generation of the methods specific to the XML marshalling framework";
		allOptions.addFlag("nomarshall","",desc,true);

        //-- implements org.exolab.castor.tests.CastroTestable?
		desc = "Implements some specific methods to allow the generated classes to be used with Castor Testing Framework";
		allOptions.addFlag("testable","",desc,true);

        //-- Process the specified command line options
        Properties options = allOptions.getOptions(args);

        //-- check for help option
        if (options.getProperty("h") != null) {
            PrintWriter pw = new PrintWriter(System.out, true);
            allOptions.printHelp(pw);
            pw.flush();
            return;
        }

        String  schemaFilename  = options.getProperty("i");
        String  packageName     = options.getProperty("package");
        String  lineSepStyle    = options.getProperty("line-separator");
        boolean force           = (options.getProperty("f") != null);
        String  typeFactory     = options.getProperty("types");
        boolean verbose         = (options.getProperty("verbose") != null);

        if (schemaFilename == null) {
            System.out.println(appName);
            allOptions.printUsage(new PrintWriter(System.out));
            return;
        }

        // -- XXX maintained temporarily
        if (typeFactory == null)
            typeFactory = options.getProperty("type-factory");

        String lineSep = System.getProperty("line.separator");
        if (lineSepStyle != null) {
            if ("win".equals(lineSepStyle)) {
                System.out.println(" - using Windows style line separation.");
                lineSep = "\r\n";
            }
            else if ("unix".equals(lineSepStyle)) {
                System.out.println(" - using UNIX style line separation.");
                lineSep = "\n";
            }
            else if ("mac".equals(lineSepStyle)) {
                System.out.println(" - using Macintosh style line separation.");
                lineSep = "\r";
            }
            else {
                System.out.print("- invalid option for line-separator: ");
                System.out.println(lineSepStyle);
                System.out.println("-- using default line separator for this platform");
            }
        }

        SourceGenerator sgen = null;
        if (typeFactory != null) {
            typeFactory = Configuration.getProperty("org.exolab.castor.builder.type." + typeFactory.toLowerCase(),typeFactory);
            try {
                sgen = new SourceGenerator((FieldInfoFactory)Class.forName(typeFactory).newInstance());
            }
            catch(Exception x) {
                System.out.print("- invalid option for types: ");
                System.out.println(typeFactory);
                System.out.println(x);
                System.out.println("-- using default source generator types");
                sgen = new SourceGenerator(); // default
            }
        }
        else {
            sgen = new SourceGenerator(); // default
        }

        sgen.setDestDir(options.getProperty("dest"));
        sgen.setLineSeparator(lineSep);
        sgen.setSuppressNonFatalWarnings(force);
        sgen.setVerbose(verbose);

        if (force)
            System.out.println("-- Suppressing non fatal warnings.");

        if (options.getProperty("nodesc") != null) {
            sgen.setDescriptorCreation(false);
            System.out.print("-- ");
            System.out.println(DISABLE_DESCRIPTORS_MSG);
		}

		if (options.getProperty("nomarshall") != null) {
		    sgen.setCreateMarshalMethods(false);
		    System.out.print("-- ");
            System.out.println(DISABLE_MARSHALL_MSG);
		}

        if (options.getProperty("testable") != null) {
		    sgen.setTestable(true);
		    System.out.print("-- ");
            System.out.println(CASTOR_TESTABLE_MSG);
		}

        try {
            sgen.generateSource(schemaFilename, packageName);
        }
        catch(java.io.FileNotFoundException fne) {
            System.out.println("unable to open XML schema file");
            return;
        }

    } //-- main
Exemplo n.º 16
0
 /**
  * Assembles a bean from an XML file.
  *
  * @param <T> the expected object type
  * @param file the path to the XML file
  * @param type the expected object type
  * @return an object assembled from this XML file
  * @throws SAXException if the internal SAX parser fails
  * @throws IOException if any IO errors occur
  */
 public <T> T build(String file, Class<T> type) throws SAXException, IOException {
   _parser.parse(new File(file), this);
   return type.cast(getBean());
 }
Exemplo n.º 17
0
  /** Receive notification of the start of an element. */
  @Override
  public void startElement(String uri, String l, String q, Attributes a) {
    /*
     * 1. Load a class that matches the element name.
     * 2. If no class found, assume the element maps to a String.
     * 3. Otherwise, construct a new object of the class with element attributes.
     */
    _logger.fine(
        S.fine(_logger)
            ? "Consider element " + l + "\n             uri " + uri + "\n               q " + q
            : null);
    ElementInfo info = new ElementInfo();

    // Record java packages defined on this element as xmlns
    for (int i = 0; i < a.getLength(); ++i) {
      _logger.fine(
          S.fine(_logger)
              ? "            attr "
                  + a.getQName(i)
                  + "="
                  + a.getValue(i)
                  + "\n                 "
                  + a.getQName(i)
                  + ":"
                  + a.getURI(i)
              : null);
      if (a.getQName(i).startsWith("xmlns:") && a.getValue(i).startsWith("java://")) {
        info.pkgs.put(a.getQName(i).substring(6), a.getValue(i).substring(7));
      }
    }

    // Resolve the package name of this element, which could be empty (default package)
    int colon = q.indexOf(':');
    if (colon > 0) {
      String xmlns = q.substring(0, colon);
      // is it defined right here?
      info.jpkg = info.pkgs.get(xmlns);
      // find a matching namespace from ancesters
      if (info.jpkg == null && !_stack.isEmpty()) {
        for (int i = _stack.size() - 1; i >= 0; --i) {
          info.jpkg = _stack.get(i).pkgs.get(xmlns);
          if (info.jpkg != null) {
            break;
          }
        }
      }
    } else if (isPrimitiveType(q)) {
      info.jpkg = "java.lang";
    } else if (!_stack.isEmpty()) {
      info.jpkg = _stack.get(_stack.size() - 1).jpkg;
    } else {
      info.jpkg = _jpkg;
    }

    _logger.fine("to create element with package = " + info.jpkg);
    try {
      info.name =
          (info.jpkg != null) ? info.jpkg + '.' + Strings.toCamelCase(l) : Strings.toCamelCase(l);
      try {
        if (info.name.endsWith("...")) {
          // Array construction
          info.type = Class.forName(info.name.substring(0, info.name.length() - 3));
          info.data = new ArrayList<Object>();
        } else {
          // Non-array construction
          int size = a.getLength();
          TypedValueGroup arguments = new TypedValueGroup();
          for (int i = 0; i < size; ++i) {
            if (!a.getQName(i).startsWith("xmlns:") && !a.getQName(i).equals("xmlns")) {
              arguments.add(guessUntypedValue(a.getQName(i), a.getValue(i)));
            }
          }
          arguments.complete();
          _logger.fine(S.fine(_logger) ? "arguments=" + arguments : null);

          if (arguments.size() > 0) {
            if (arguments.size() == 1 && "java.lang".equals(info.jpkg)) {
              info.inst.put(
                  "@as",
                  Strings.toCamelCase(
                      arguments.get(0).name, '-', false)); // respect original spelling
              info.data = arguments.get(0).get(0).data;
              info.type = arguments.get(0).get(0).type;
            } else {
              Exception last = null;
              Object[] args = new Object[arguments.size()];
              while (arguments.load(args, 0)) {
                try {
                  _logger.fine(
                      S.fine(_logger)
                          ? "to create " + info.name + " with args: " + args.length + args(args)
                          : null);
                  info.data = _factory.create(info.name, args);
                  info.type = info.data.getClass();
                  break;
                } catch (InvocationTargetException x) {
                  throw x;
                } catch (Exception x) {
                  last = x;
                  _logger.fine(
                      "failure in creating " + info.name + ": probing for other constructors");
                }
              }

              if (info.data == null) {
                throw last;
              }
            }
          } else {
            _logger.fine("Create " + info.name + " with the default constructor");
            info.data = _factory.create(info.name);
            info.type = info.data.getClass();
          }
        }
      } catch (ClassNotFoundException x) {
        // no class by the element name is found, assumed String
        if (!_lenient) {
          throw new BeanAssemblyException("No class associated with element " + q);
        } else {
          _logger.log(Level.WARNING, "can't find class " + info.name, x);
        }
      }
      _stack.add(info);
      // _logger.fine(">>ElementInfo: " + info.type.getName() + " in " + info);
      // all other exceptions indicate mismatches between the beans and the XML schema
    } catch (Exception x) {
      if (!_lenient) {
        throw new BeanAssemblyException("Failed to assemble bean from element " + q, x);
      } else {
        _logger.log(Level.SEVERE, "can't create object for this element", x);
      }
    }
  }
Exemplo n.º 18
0
 /**
  * Assembles a bean from an XML stream.
  *
  * @param <T> the expected object type
  * @param stream the XML input stream
  * @param type the expected object type
  * @return an object assembled from this XML stream
  * @throws SAXException if the internal SAX parser fails
  * @throws IOException if any IO errors occur
  */
 public <T> T build(InputStream stream, Class<T> type) throws SAXException, IOException {
   _parser.parse(stream, this);
   return type.cast(getBean());
 }
Exemplo n.º 19
0
  private TypedValues guessUntypedValue(String name, String value) {
    TypedValues list = new TypedValues(name);

    if (value.startsWith("java:")) { // possible java static reference
      int dot;
      if (value.equals("java:null")) {
        list.add(new TypedValue(Object.class, null));
      } else if (value.charAt(5) == '$') { // reference to a local object (assemble @id)
        ElementInfo element = _local.get(value.substring(6));
        if (element != null) {
          list.add(new TypedValue(element.type, element.data));
        }
      } else if ((dot = value.lastIndexOf('.')) > 5) {
        try {
          // public static refernce? (don't override access control)
          _logger.fine("public static refernce? " + value);
          Object object =
              Class.forName(value.substring(5, dot)).getField(value.substring(dot + 1)).get(null);
          Class<?> type = object.getClass();
          list.add(new TypedValue(type, object));
          // automatic upscaling to larger types
          if (type == Byte.class) {
            object = new Short(((Byte) object).byteValue());
            list.add(new TypedValue(Short.class, object));
            type = Short.class;
          }
          if (type == Short.class) {
            object = new Integer(((Short) object).shortValue());
            list.add(new TypedValue(Integer.class, object));
            type = Integer.class;
          }
          if (type == Integer.class) {
            object = new Long(((Integer) object).intValue());
            list.add(new TypedValue(Long.class, object));
            type = Long.class;
          }
          if (type == Long.class) {
            object = new Float(((Long) object).longValue());
            list.add(new TypedValue(Float.class, object));
            type = Float.class;
          }
          if (type == Float.class) {
            object = new Double(((Float) object).floatValue());
            list.add(new TypedValue(Double.class, object));
          }
        } catch (Exception x) {
          _logger.fine(value + " looked like a static reference but is not: " + x.getMessage());
          // class reference?
          guessClassReference(list, value.substring(5));
        }
      } else { // no '.' at all
        // class reference?
        guessClassReference(list, value.substring(5));
      }
    } else if (value.equals("true")) {
      list.add(new TypedValue(Boolean.class, Boolean.TRUE));
    } else if (value.equals("false")) {
      list.add(new TypedValue(Boolean.class, Boolean.FALSE));
    } else {
      // numbers? multiple possibilities
      try {
        list.add(new TypedValue(Integer.class, Integer.valueOf(value)));
      } catch (Exception x) {
      }
      try {
        list.add(new TypedValue(Long.class, Long.valueOf(value)));
      } catch (Exception x) {
      }
      try {
        list.add(new TypedValue(Float.class, Float.valueOf(value)));
      } catch (Exception x) {
      }
      try {
        list.add(new TypedValue(Double.class, Double.valueOf(value)));
      } catch (Exception x) {
      }
    }

    // always try String as the last resort
    list.add(new TypedValue(String.class, value));

    return list;
  }