示例#1
0
  /** Process the source tree to the output result. */
  public void transform(Source source, Result result) throws TransformerException {

    XSLProcessorImpl processor = init(result);

    try {
      // now find an adapter for the input source
      XMLReader reader = _factory.getReader(source);
      processor.setSourceReader(reader);
      String sysId = source.getSystemId();
      InputSource src = SAXSource.sourceToInputSource(source);
      if (src == null) {
        if (sysId == null) {
          src = new InputSource("dummy");
        } else {
          src = new InputSource(sysId);
        }
      }

      // FIXME: set error handler
      processor.parse(src);

    } catch (Exception ex) {
      throw new TransformerException(ex);
    }
  }
 @POST
 @Path("source")
 @Consumes("text/xml")
 @Produces("text/plain")
 public byte[] xsltPost(Source source) throws IOException {
   final InputSource inputSource = SAXSource.sourceToInputSource(source);
   return TestUtils.getByteArray(inputSource.getByteStream());
 }
  public static Envelope createEnvelope(Source src, SOAPPartImpl soapPart) throws SOAPException {
    // Insert SAX filter to disallow Document Type Declarations since
    // they are not legal in SOAP
    SAXParser saxParser = null;
    if (src instanceof StreamSource) {
      if (src instanceof JAXMStreamSource) {
        try {
          ((JAXMStreamSource) src).reset();
        } catch (java.io.IOException ioe) {
          log.severe("SAAJ0515.source.reset.exception");
          throw new SOAPExceptionImpl(ioe);
        }
      }
      try {
        saxParser = parserPool.get();
      } catch (Exception e) {
        log.severe("SAAJ0601.util.newSAXParser.exception");
        throw new SOAPExceptionImpl("Couldn't get a SAX parser while constructing a envelope", e);
      }
      InputSource is = SAXSource.sourceToInputSource(src);
      XMLReader rejectFilter;
      try {
        rejectFilter = new RejectDoctypeSaxFilter(saxParser);
      } catch (Exception ex) {
        log.severe("SAAJ0510.soap.cannot.create.envelope");
        throw new SOAPExceptionImpl("Unable to create envelope from given source: ", ex);
      }
      src = new SAXSource(rejectFilter, is);
    }

    try {
      Transformer transformer = EfficientStreamingTransformer.newTransformer();
      DOMResult result = new DOMResult(soapPart);
      transformer.transform(src, result);

      Envelope env = (Envelope) soapPart.getEnvelope();
      if (saxParser != null) {
        parserPool.put(saxParser);
      }
      return env;
    } catch (Exception ex) {
      if (ex instanceof SOAPVersionMismatchException) {
        throw (SOAPVersionMismatchException) ex;
      }
      log.severe("SAAJ0511.soap.cannot.create.envelope");
      throw new SOAPExceptionImpl("Unable to create envelope from given source: ", ex);
    }
  }
示例#4
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;
  }
  /**
   * Get an instance of a DTM, loaded with the content from the specified source. If the unique flag
   * is true, a new instance will always be returned. Otherwise it is up to the DTMManager to return
   * a new instance or an instance that it already created and may be being used by someone else. (I
   * think more parameters will need to be added for error handling, and entity resolution).
   *
   * @param source the specification of the source object.
   * @param unique true if the returned DTM must be unique, probably because it is going to be
   *     mutated.
   * @param whiteSpaceFilter Enables filtering of whitespace nodes, and may be null.
   * @param incremental true if the DTM should be built incrementally, if possible.
   * @param doIndexing true if the caller considers it worth it to use indexing schemes.
   * @param hasUserReader true if <code>source</code> is a <code>SAXSource</code> object that has an
   *     <code>XMLReader</code>, that was specified by the user.
   * @param size Specifies initial size of tables that represent the DTM
   * @param buildIdIndex true if the id index table should be built.
   * @param newNameTable true if we want to use a separate ExpandedNameTable for this DTM.
   * @return a non-null DTM reference.
   */
  public DTM getDTM(
      Source source,
      boolean unique,
      DTMWSFilter whiteSpaceFilter,
      boolean incremental,
      boolean doIndexing,
      boolean hasUserReader,
      int size,
      boolean buildIdIndex,
      boolean newNameTable) {
    if (DEBUG && null != source) {
      System.out.println(
          "Starting " + (unique ? "UNIQUE" : "shared") + " source: " + source.getSystemId());
    }

    int dtmPos = getFirstFreeDTMID();
    int documentID = dtmPos << IDENT_DTM_NODE_BITS;

    if ((null != source) && source instanceof StAXSource) {
      final StAXSource staxSource = (StAXSource) source;
      StAXEvent2SAX staxevent2sax = null;
      StAXStream2SAX staxStream2SAX = null;
      if (staxSource.getXMLEventReader() != null) {
        final XMLEventReader xmlEventReader = staxSource.getXMLEventReader();
        staxevent2sax = new StAXEvent2SAX(xmlEventReader);
      } else if (staxSource.getXMLStreamReader() != null) {
        final XMLStreamReader xmlStreamReader = staxSource.getXMLStreamReader();
        staxStream2SAX = new StAXStream2SAX(xmlStreamReader);
      }

      SAXImpl dtm;

      if (size <= 0) {
        dtm =
            new SAXImpl(
                this,
                source,
                documentID,
                whiteSpaceFilter,
                null,
                doIndexing,
                DTMDefaultBase.DEFAULT_BLOCKSIZE,
                buildIdIndex,
                newNameTable);
      } else {
        dtm =
            new SAXImpl(
                this,
                source,
                documentID,
                whiteSpaceFilter,
                null,
                doIndexing,
                size,
                buildIdIndex,
                newNameTable);
      }

      dtm.setDocumentURI(source.getSystemId());

      addDTM(dtm, dtmPos, 0);

      try {
        if (staxevent2sax != null) {
          staxevent2sax.setContentHandler(dtm);
          staxevent2sax.parse();
        } else if (staxStream2SAX != null) {
          staxStream2SAX.setContentHandler(dtm);
          staxStream2SAX.parse();
        }

      } catch (RuntimeException re) {
        throw re;
      } catch (Exception e) {
        throw new com.sun.org.apache.xml.internal.utils.WrappedRuntimeException(e);
      }

      return dtm;
    } else if ((null != source) && source instanceof DOMSource) {
      final DOMSource domsrc = (DOMSource) source;
      final org.w3c.dom.Node node = domsrc.getNode();
      final DOM2SAX dom2sax = new DOM2SAX(node);

      SAXImpl dtm;

      if (size <= 0) {
        dtm =
            new SAXImpl(
                this,
                source,
                documentID,
                whiteSpaceFilter,
                null,
                doIndexing,
                DTMDefaultBase.DEFAULT_BLOCKSIZE,
                buildIdIndex,
                newNameTable);
      } else {
        dtm =
            new SAXImpl(
                this,
                source,
                documentID,
                whiteSpaceFilter,
                null,
                doIndexing,
                size,
                buildIdIndex,
                newNameTable);
      }

      dtm.setDocumentURI(source.getSystemId());

      addDTM(dtm, dtmPos, 0);

      dom2sax.setContentHandler(dtm);

      try {
        dom2sax.parse();
      } catch (RuntimeException re) {
        throw re;
      } catch (Exception e) {
        throw new com.sun.org.apache.xml.internal.utils.WrappedRuntimeException(e);
      }

      return dtm;
    } else {
      boolean isSAXSource = (null != source) ? (source instanceof SAXSource) : true;
      boolean isStreamSource = (null != source) ? (source instanceof StreamSource) : false;

      if (isSAXSource || isStreamSource) {
        XMLReader reader;
        InputSource xmlSource;

        if (null == source) {
          xmlSource = null;
          reader = null;
          hasUserReader = false; // Make sure the user didn't lie
        } else {
          reader = getXMLReader(source);
          xmlSource = SAXSource.sourceToInputSource(source);

          String urlOfSource = xmlSource.getSystemId();

          if (null != urlOfSource) {
            try {
              urlOfSource = SystemIDResolver.getAbsoluteURI(urlOfSource);
            } catch (Exception e) {
              // %REVIEW% Is there a better way to send a warning?
              System.err.println("Can not absolutize URL: " + urlOfSource);
            }

            xmlSource.setSystemId(urlOfSource);
          }
        }

        // Create the basic SAX2DTM.
        SAXImpl dtm;
        if (size <= 0) {
          dtm =
              new SAXImpl(
                  this,
                  source,
                  documentID,
                  whiteSpaceFilter,
                  null,
                  doIndexing,
                  DTMDefaultBase.DEFAULT_BLOCKSIZE,
                  buildIdIndex,
                  newNameTable);
        } else {
          dtm =
              new SAXImpl(
                  this,
                  source,
                  documentID,
                  whiteSpaceFilter,
                  null,
                  doIndexing,
                  size,
                  buildIdIndex,
                  newNameTable);
        }

        // Go ahead and add the DTM to the lookup table.  This needs to be
        // done before any parsing occurs. Note offset 0, since we've just
        // created a new DTM.
        addDTM(dtm, dtmPos, 0);

        if (null == reader) {
          // Then the user will construct it themselves.
          return dtm;
        }

        reader.setContentHandler(dtm.getBuilder());

        if (!hasUserReader || null == reader.getDTDHandler()) {
          reader.setDTDHandler(dtm);
        }

        if (!hasUserReader || null == reader.getErrorHandler()) {
          reader.setErrorHandler(dtm);
        }

        try {
          reader.setProperty("http://xml.org/sax/properties/lexical-handler", dtm);
        } catch (SAXNotRecognizedException e) {
        } catch (SAXNotSupportedException e) {
        }

        try {
          reader.parse(xmlSource);
        } catch (RuntimeException re) {
          throw re;
        } catch (Exception e) {
          throw new com.sun.org.apache.xml.internal.utils.WrappedRuntimeException(e);
        } finally {
          if (!hasUserReader) {
            releaseXMLReader(reader);
          }
        }

        if (DUMPTREE) {
          System.out.println("Dumping SAX2DOM");
          dtm.dumpDTM(System.err);
        }

        return dtm;
      } else {
        // It should have been handled by a derived class or the caller
        // made a mistake.
        throw new DTMException(
            XMLMessages.createXMLMessage(
                XMLErrorResources.ER_NOT_SUPPORTED, new Object[] {source}));
      }
    }
  }