private void parseSAX(Source source, ContentHandler handler)
      throws TransformerConfigurationException {
    try {
      if (source instanceof SAXSource) {
        SAXSource saxSource = (SAXSource) source;

        XMLReader reader = saxSource.getXMLReader();
        InputSource inputSource = saxSource.getInputSource();

        reader.setContentHandler(handler);

        reader.parse(inputSource);
      } else if (source instanceof StreamSource) {

        XmlParser parser = new Xml();

        parser.setContentHandler(handler);

        ReadStream rs = openPath(source);
        try {
          parser.parse(rs);
        } finally {
          rs.close();
        }
      } else if (source instanceof DOMSource) {
        DOMSource domSource = (DOMSource) source;

        Node node = domSource.getNode();

        XmlUtil.toSAX(node, handler);
      }
    } catch (Exception e) {
      throw new TransformerConfigurationException(e);
    }
  }
예제 #2
0
  private CharSequence readFile(String href, String baseURI) throws XPathException {
    try {

      // Use resolver as it does a series of tasks for us, and use "binary" mode
      final TransformerURIResolver resolver =
          new TransformerURIResolver(
              null, PipelineContext.get(), null, XMLParsing.ParserConfiguration.PLAIN, "binary");

      final StringBuilder sb = new StringBuilder(1024);

      // Get SAX source using crazy SAX API
      // Source produces a binary document (content Base64-encoded)
      final SAXSource source = (SAXSource) resolver.resolve(href, baseURI);
      final XMLReader xmlReader = source.getXMLReader();
      xmlReader.setContentHandler(
          new XMLReceiverAdapter() {
            public void characters(char ch[], int start, int length) throws SAXException {
              // Append Base64-encoded text only
              sb.append(ch, start, length);
            }
          });
      xmlReader.parse(source.getInputSource());

      // Return content formatted as Base64
      return sb.toString();
    } catch (Exception e) {
      throw new XPathException(e);
    }
  }
  /**
   * Create a compiled stylesheet from an input stream.
   *
   * @param source the source stream
   * @return the compiled stylesheet
   */
  public Templates newTemplates(Source source) throws TransformerConfigurationException {
    String systemId = source.getSystemId();

    try {
      if (systemId != null) {
        StylesheetImpl stylesheet = loadPrecompiledStylesheet(systemId, systemId);

        if (stylesheet != null) return stylesheet;
      }

      if (source instanceof DOMSource) {
        Node node = ((DOMSource) source).getNode();

        return generateFromNode(node, systemId);
      } else if (source instanceof SAXSource) {
        SAXSource saxSource = (SAXSource) source;
        XMLReader reader = saxSource.getXMLReader();
        InputSource inputSource = saxSource.getInputSource();

        Document doc = new QDocument();
        DOMBuilder builder = new DOMBuilder();
        builder.init(doc);
        reader.setContentHandler(builder);

        reader.parse(inputSource);

        return generateFromNode(doc, systemId);
      }

      ReadStream rs = openPath(source);
      try {
        Path path = rs.getPath();

        Document doc = parseXSL(rs);

        if (systemId != null) {
          String mangledName = getMangledName(systemId);
          Path genPath = getWorkPath().lookup(mangledName);

          genPath.setUserPath(systemId);

          return generate(doc, genPath);
        } else return generateFromNode(doc, null);
      } finally {
        if (rs != null) rs.close();
      }
    } catch (TransformerConfigurationException e) {
      throw e;
    } catch (Exception e) {
      throw new XslParseException(e);
    }
  }
  public Object unmarshal0(Source source, JaxBeanInfo expectedType) throws JAXBException {
    if (source instanceof SAXSource) {
      SAXSource ss = (SAXSource) source;

      XMLReader reader = ss.getXMLReader();
      if (reader == null) reader = getXMLReader();

      return unmarshal0(reader, ss.getInputSource(), expectedType);
    }
    if (source instanceof StreamSource) {
      return unmarshal0(
          getXMLReader(), streamSourceToInputSource((StreamSource) source), expectedType);
    }
    if (source instanceof DOMSource)
      return unmarshal0(((DOMSource) source).getNode(), expectedType);

    // we don't handle other types of Source
    throw new IllegalArgumentException();
  }
  @Override
  public <T> JAXBElement<T> unmarshal(Source source, Class<T> expectedType) throws JAXBException {
    if (source instanceof SAXSource) {
      SAXSource ss = (SAXSource) source;

      XMLReader reader = ss.getXMLReader();
      if (reader == null) reader = getXMLReader();

      return unmarshal(reader, ss.getInputSource(), expectedType);
    }
    if (source instanceof StreamSource) {
      return unmarshal(
          getXMLReader(), streamSourceToInputSource((StreamSource) source), expectedType);
    }
    if (source instanceof DOMSource) return unmarshal(((DOMSource) source).getNode(), expectedType);

    // we don't handle other types of Source
    throw new IllegalArgumentException();
  }
예제 #6
0
  public Schema newSchema(Source[] schemas) throws SAXException {

    // this will let the loader store parsed Grammars into the pool.
    XMLGrammarPoolImplExtension pool = new XMLGrammarPoolImplExtension();
    fXMLGrammarPoolWrapper.setGrammarPool(pool);

    XMLInputSource[] xmlInputSources = new XMLInputSource[schemas.length];
    InputStream inputStream;
    Reader reader;
    for (int i = 0; i < schemas.length; i++) {
      Source source = schemas[i];
      if (source instanceof StreamSource) {
        StreamSource streamSource = (StreamSource) source;
        String publicId = streamSource.getPublicId();
        String systemId = streamSource.getSystemId();
        inputStream = streamSource.getInputStream();
        reader = streamSource.getReader();
        xmlInputSources[i] = new XMLInputSource(publicId, systemId, null);
        xmlInputSources[i].setByteStream(inputStream);
        xmlInputSources[i].setCharacterStream(reader);
      } else if (source instanceof SAXSource) {
        SAXSource saxSource = (SAXSource) source;
        InputSource inputSource = saxSource.getInputSource();
        if (inputSource == null) {
          throw new SAXException(
              JAXPValidationMessageFormatter.formatMessage(
                  Locale.getDefault(), "SAXSourceNullInputSource", null));
        }
        xmlInputSources[i] = new SAXInputSource(saxSource.getXMLReader(), inputSource);
      } else if (source instanceof DOMSource) {
        DOMSource domSource = (DOMSource) source;
        Node node = domSource.getNode();
        String systemID = domSource.getSystemId();
        xmlInputSources[i] = new DOMInputSource(node, systemID);
      } else if (source == null) {
        throw new NullPointerException(
            JAXPValidationMessageFormatter.formatMessage(
                Locale.getDefault(), "SchemaSourceArrayMemberNull", null));
      } else {
        throw new IllegalArgumentException(
            JAXPValidationMessageFormatter.formatMessage(
                Locale.getDefault(),
                "SchemaFactorySourceUnrecognized",
                new Object[] {source.getClass().getName()}));
      }
    }

    try {
      fXMLSchemaLoader.loadGrammar(xmlInputSources);
    } catch (XNIException e) {
      // this should have been reported to users already.
      throw Util.toSAXException(e);
    } catch (IOException e) {
      // this hasn't been reported, so do so now.
      SAXParseException se = new SAXParseException(e.getMessage(), null, e);
      fErrorHandler.error(se);
      throw se; // and we must throw it.
    }

    // Clear reference to grammar pool.
    fXMLGrammarPoolWrapper.setGrammarPool(null);

    // Select Schema implementation based on grammar count.
    final int grammarCount = pool.getGrammarCount();
    if (grammarCount > 1) {
      return new XMLSchema(new ReadOnlyGrammarPool(pool));
    } else if (grammarCount == 1) {
      Grammar[] grammars = pool.retrieveInitialGrammarSet(XMLGrammarDescription.XML_SCHEMA);
      return new SimpleXMLSchema(grammars[0]);
    } else {
      return EmptyXMLSchema.getInstance();
    }
  }
예제 #7
0
 private void tryAddEntityResolver(SAXSource source) {
   // expecting source to have not null XMLReader
   if (this.entityResolver != null && source != null) {
     source.getXMLReader().setEntityResolver(this.entityResolver);
   }
 }
예제 #8
0
  public void validate(Source source, Result result) throws SAXException, IOException {
    if (result instanceof SAXResult || result == null) {
      final SAXSource saxSource = (SAXSource) source;
      final SAXResult saxResult = (SAXResult) result;

      if (result != null) {
        setContentHandler(saxResult.getHandler());
      }

      try {
        XMLReader reader = saxSource.getXMLReader();
        if (reader == null) {
          // create one now
          SAXParserFactory spf = SAXParserFactory.newInstance();
          spf.setNamespaceAware(true);
          try {
            reader = spf.newSAXParser().getXMLReader();
            // If this is a Xerces SAX parser, set the security manager if there is one
            if (reader instanceof com.sun.org.apache.xerces.internal.parsers.SAXParser) {
              SecurityManager securityManager =
                  (SecurityManager) fComponentManager.getProperty(SECURITY_MANAGER);
              if (securityManager != null) {
                try {
                  reader.setProperty(SECURITY_MANAGER, securityManager);
                }
                // Ignore the exception if the security manager cannot be set.
                catch (SAXException exc) {
                }
              }
            }
          } catch (Exception e) {
            // this is impossible, but better safe than sorry
            throw new FactoryConfigurationError(e);
          }
        }

        // If XML names and Namespace URIs are already internalized we
        // can avoid running them through the SymbolTable.
        try {
          fStringsInternalized = reader.getFeature(STRING_INTERNING);
        } catch (SAXException exc) {
          // The feature isn't recognized or getting it is not supported.
          // In either case, assume that strings are not internalized.
          fStringsInternalized = false;
        }

        ErrorHandler errorHandler = fComponentManager.getErrorHandler();
        reader.setErrorHandler(
            errorHandler != null ? errorHandler : DraconianErrorHandler.getInstance());
        reader.setEntityResolver(fResolutionForwarder);
        fResolutionForwarder.setEntityResolver(fComponentManager.getResourceResolver());
        reader.setContentHandler(this);
        reader.setDTDHandler(this);

        InputSource is = saxSource.getInputSource();
        reader.parse(is);
      } finally {
        // release the reference to user's handler ASAP
        setContentHandler(null);
      }
      return;
    }
    throw new IllegalArgumentException(
        JAXPValidationMessageFormatter.formatMessage(
            Locale.getDefault(),
            "SourceResultMismatch",
            new Object[] {source.getClass().getName(), result.getClass().getName()}));
  }
예제 #9
0
파일: Util.java 프로젝트: srnsw/xena
  /** Creates a SAX2 InputSource object from a TrAX Source object */
  public static InputSource getInputSource(XSLTC xsltc, Source source)
      throws TransformerConfigurationException {
    InputSource input = null;

    String systemId = source.getSystemId();

    try {
      // Try to get InputSource from SAXSource input
      if (source instanceof SAXSource) {
        final SAXSource sax = (SAXSource) source;
        input = sax.getInputSource();
        // Pass the SAX parser to the compiler
        try {
          XMLReader reader = sax.getXMLReader();

          /*
           * Fix for bug 24695
           * According to JAXP 1.2 specification if a SAXSource
           * is created using a SAX InputSource the Transformer or
           * TransformerFactory creates a reader via the
           * XMLReaderFactory if setXMLReader is not used
           */

          if (reader == null) {
            try {
              reader = XMLReaderFactory.createXMLReader();
            } catch (Exception e) {
              try {

                // Incase there is an exception thrown
                // resort to JAXP
                SAXParserFactory parserFactory = SAXParserFactory.newInstance();
                parserFactory.setNamespaceAware(true);

                if (xsltc.isSecureProcessing()) {
                  try {
                    parserFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
                  } catch (org.xml.sax.SAXException se) {
                  }
                }

                reader = parserFactory.newSAXParser().getXMLReader();

              } catch (ParserConfigurationException pce) {
                throw new TransformerConfigurationException("ParserConfigurationException", pce);
              }
            }
          }
          reader.setFeature("http://xml.org/sax/features/namespaces", true);
          reader.setFeature("http://xml.org/sax/features/namespace-prefixes", false);

          xsltc.setXMLReader(reader);
        } catch (SAXNotRecognizedException snre) {
          throw new TransformerConfigurationException("SAXNotRecognizedException ", snre);
        } catch (SAXNotSupportedException snse) {
          throw new TransformerConfigurationException("SAXNotSupportedException ", snse);
        } catch (SAXException se) {
          throw new TransformerConfigurationException("SAXException ", se);
        }

      }
      // handle  DOMSource
      else if (source instanceof DOMSource) {
        final DOMSource domsrc = (DOMSource) source;
        final Document dom = (Document) domsrc.getNode();
        final DOM2SAX dom2sax = new DOM2SAX(dom);
        xsltc.setXMLReader(dom2sax);

        // Try to get SAX InputSource from DOM Source.
        input = SAXSource.sourceToInputSource(source);
        if (input == null) {
          input = new InputSource(domsrc.getSystemId());
        }
      }
      // Try to get InputStream or Reader from StreamSource
      else if (source instanceof StreamSource) {
        final StreamSource stream = (StreamSource) source;
        final InputStream istream = stream.getInputStream();
        final Reader reader = stream.getReader();
        xsltc.setXMLReader(null); // Clear old XML reader

        // Create InputSource from Reader or InputStream in Source
        if (istream != null) {
          input = new InputSource(istream);
        } else if (reader != null) {
          input = new InputSource(reader);
        } else {
          input = new InputSource(systemId);
        }
      } else {
        ErrorMsg err = new ErrorMsg(ErrorMsg.JAXP_UNKNOWN_SOURCE_ERR);
        throw new TransformerConfigurationException(err.toString());
      }
      input.setSystemId(systemId);
    } catch (NullPointerException e) {
      ErrorMsg err = new ErrorMsg(ErrorMsg.JAXP_NO_SOURCE_ERR, "TransformerFactory.newTemplates()");
      throw new TransformerConfigurationException(err.toString());
    } catch (SecurityException e) {
      ErrorMsg err = new ErrorMsg(ErrorMsg.FILE_ACCESS_ERR, systemId);
      throw new TransformerConfigurationException(err.toString());
    }
    return input;
  }