Exemple #1
0
  public void marshal(Object obj, Result result) throws JAXBException {
    // XMLSerializable so = Util.toXMLSerializable(obj);
    XMLSerializable so = context.getGrammarInfo().castToXMLSerializable(obj);

    if (so == null) throw new MarshalException(Messages.format(Messages.NOT_MARSHALLABLE));

    if (result instanceof SAXResult) {
      write(so, ((SAXResult) result).getHandler());
      return;
    }
    if (result instanceof DOMResult) {
      Node node = ((DOMResult) result).getNode();

      if (node == null) {
        try {
          DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
          dbf.setNamespaceAware(true);
          DocumentBuilder db = dbf.newDocumentBuilder();
          Document doc = db.newDocument();
          ((DOMResult) result).setNode(doc);
          write(so, new SAX2DOMEx(doc));
        } catch (ParserConfigurationException pce) {
          throw new JAXBAssertionError(pce);
        }
      } else {
        write(so, new SAX2DOMEx(node));
      }

      return;
    }
    if (result instanceof StreamResult) {
      StreamResult sr = (StreamResult) result;
      XMLWriter w = null;

      if (sr.getWriter() != null) w = createWriter(sr.getWriter());
      else if (sr.getOutputStream() != null) w = createWriter(sr.getOutputStream());
      else if (sr.getSystemId() != null) {
        String fileURL = sr.getSystemId();

        if (fileURL.startsWith("file:///")) {
          if (fileURL.substring(8).indexOf(":") > 0) fileURL = fileURL.substring(8);
          else fileURL = fileURL.substring(7);
        } // otherwise assume that it's a file name

        try {
          w = createWriter(new FileOutputStream(fileURL));
        } catch (IOException e) {
          throw new MarshalException(e);
        }
      }

      if (w == null) throw new IllegalArgumentException();

      write(so, w);
      return;
    }

    // unsupported parameter type
    throw new MarshalException(Messages.format(Messages.UNSUPPORTED_RESULT));
  }
  public void validate(Source source, Result result) throws SAXException, IOException {
    if (result instanceof StreamResult || result == null) {
      final StreamSource streamSource = (StreamSource) source;
      final StreamResult streamResult = (StreamResult) result;
      XMLInputSource input =
          new XMLInputSource(streamSource.getPublicId(), streamSource.getSystemId(), null);
      input.setByteStream(streamSource.getInputStream());
      input.setCharacterStream(streamSource.getReader());

      // Gets the parser configuration. We'll create and initialize a new one, if we
      // haven't created one before or if the previous one was garbage collected.
      boolean newConfig = false;
      XMLParserConfiguration config = (XMLParserConfiguration) fConfiguration.get();
      if (config == null) {
        config = initialize();
        newConfig = true;
      }
      // If settings have changed on the component manager, refresh the error handler and entity
      // resolver.
      else if (fComponentManager.getFeature(PARSER_SETTINGS)) {
        config.setProperty(ENTITY_RESOLVER, fComponentManager.getProperty(ENTITY_RESOLVER));
        config.setProperty(ERROR_HANDLER, fComponentManager.getProperty(ERROR_HANDLER));
        config.setProperty(SECURITY_MANAGER, fComponentManager.getProperty(SECURITY_MANAGER));
      }

      // prepare for parse
      fComponentManager.reset();

      if (streamResult != null) {
        if (fSerializerFactory == null) {
          fSerializerFactory = SerializerFactory.getSerializerFactory(Method.XML);
        }

        // there doesn't seem to be a way to reset a serializer, so we need to make
        // a new one each time.
        Serializer ser;
        if (streamResult.getWriter() != null) {
          ser = fSerializerFactory.makeSerializer(streamResult.getWriter(), new OutputFormat());
        } else if (streamResult.getOutputStream() != null) {
          ser =
              fSerializerFactory.makeSerializer(streamResult.getOutputStream(), new OutputFormat());
        } else if (streamResult.getSystemId() != null) {
          String uri = streamResult.getSystemId();
          OutputStream out = XMLEntityManager.createOutputStream(uri);
          ser = fSerializerFactory.makeSerializer(out, new OutputFormat());
        } else {
          throw new IllegalArgumentException(
              JAXPValidationMessageFormatter.formatMessage(
                  fComponentManager.getLocale(), "StreamResultNotInitialized", null));
        }

        // we're using the parser only as an XNI-to-SAX converter,
        // so that we can use the SAX-based serializer
        SAXParser parser = (SAXParser) fParser.get();
        if (newConfig || parser == null) {
          parser = new SAXParser(config);
          fParser = new SoftReference(parser);
        } else {
          parser.reset();
        }
        config.setDocumentHandler(fSchemaValidator);
        fSchemaValidator.setDocumentHandler(parser);
        parser.setContentHandler(ser.asContentHandler());
      } else {
        fSchemaValidator.setDocumentHandler(null);
      }

      try {
        config.parse(input);
      } catch (XMLParseException e) {
        throw Util.toSAXParseException(e);
      } catch (XNIException e) {
        throw Util.toSAXException(e);
      } finally {
        // release the references to the SAXParser and Serializer
        fSchemaValidator.setDocumentHandler(null);
      }

      return;
    }
    throw new IllegalArgumentException(
        JAXPValidationMessageFormatter.formatMessage(
            fComponentManager.getLocale(),
            "SourceResultMismatch",
            new Object[] {source.getClass().getName(), result.getClass().getName()}));
  }
  /**
   * Build the JAXB model and generate the schemas based on tha data
   *
   * @param extraFiles additional files.
   * @return class to {@link QName} resolver.
   */
  private Resolver buildModelAndSchemas(
      Map<String, ApplicationDescription.ExternalGrammar> extraFiles) {

    // Lets get all candidate classes so we can create the JAX-B context
    // include any @XmlSeeAlso references.

    Set<Class> classSet = new HashSet<Class>(seeAlsoClasses);

    for (TypeCallbackPair pair : nameCallbacks) {
      final GenericType genericType = pair.genericType;
      Class<?> clazz = genericType.getRawType();

      // Is this class itself interesting?

      if (clazz.getAnnotation(XmlRootElement.class) != null) {
        classSet.add(clazz);
      } else if (SPECIAL_GENERIC_TYPES.contains(clazz)) {

        Type type = genericType.getType();
        if (type instanceof ParameterizedType) {
          Type parameterType = ((ParameterizedType) type).getActualTypeArguments()[0];
          if (parameterType instanceof Class) {
            classSet.add((Class) parameterType);
          }
        }
      }
    }

    // Create a JAX-B context, and use this to generate us a bunch of
    // schema objects

    JAXBIntrospector introspector = null;

    try {
      JAXBContext context = JAXBContext.newInstance(classSet.toArray(new Class[classSet.size()]));

      final List<StreamResult> results = new ArrayList<StreamResult>();

      context.generateSchema(
          new SchemaOutputResolver() {

            int counter = 0;

            @Override
            public Result createOutput(String namespaceUri, String suggestedFileName) {
              StreamResult result = new StreamResult(new CharArrayWriter());
              result.setSystemId("xsd" + (counter++) + ".xsd");
              results.add(result);
              return result;
            }
          });

      // Store the new files for later use
      //

      for (StreamResult result : results) {
        CharArrayWriter writer = (CharArrayWriter) result.getWriter();
        byte[] contents = writer.toString().getBytes("UTF8");
        extraFiles.put(
            result.getSystemId(),
            new ApplicationDescription.ExternalGrammar(
                MediaType
                    .APPLICATION_XML_TYPE, // I don't think there is a specific media type for XML
                                           // Schema
                contents));
      }

      // Create an introspector
      //

      introspector = context.createJAXBIntrospector();

    } catch (JAXBException e) {
      LOGGER.log(Level.SEVERE, "Failed to generate the schema for the JAX-B elements", e);
    } catch (IOException e) {
      LOGGER.log(
          Level.SEVERE,
          "Failed to generate the schema for the JAX-B elements due to an IO error",
          e);
    }

    // Create introspector

    if (introspector != null) {
      final JAXBIntrospector copy = introspector;

      return new Resolver() {

        public QName resolve(Class type) {

          Object parameterClassInstance = null;
          try {
            Constructor<?> defaultConstructor = type.getDeclaredConstructor();
            defaultConstructor.setAccessible(true);
            parameterClassInstance = defaultConstructor.newInstance();
          } catch (InstantiationException ex) {
            LOGGER.log(Level.FINE, null, ex);
          } catch (IllegalAccessException ex) {
            LOGGER.log(Level.FINE, null, ex);
          } catch (IllegalArgumentException ex) {
            LOGGER.log(Level.FINE, null, ex);
          } catch (InvocationTargetException ex) {
            LOGGER.log(Level.FINE, null, ex);
          } catch (SecurityException ex) {
            LOGGER.log(Level.FINE, null, ex);
          } catch (NoSuchMethodException ex) {
            LOGGER.log(Level.FINE, null, ex);
          }

          if (parameterClassInstance == null) {
            return null;
          }

          try {
            return copy.getElementName(parameterClassInstance);
          } catch (NullPointerException e) {
            // EclipseLink throws an NPE if an object annotated with @XmlType and without the
            // @XmlRootElement
            // annotation is passed as a parameter of #getElementName method.
            return null;
          }
        }
      };
    } else {
      return null; // No resolver created
    }
  }